Search Unity

Strange Warping from RBody velocity

Discussion in 'Scripting' started by IchBinJager, Jun 6, 2017.

  1. IchBinJager

    IchBinJager

    Joined:
    Dec 23, 2014
    Posts:
    127
    When I try to set Rigidbody2D velocity it skips and warps everywhere;

    Code (csharp):
    1.  
    2. RBody.velocity = new Vector2(-transform.up.x, -transform.up.y) * 2;
    3.  
    Why is it doing this?
     
  2. Laperen

    Laperen

    Joined:
    Feb 1, 2016
    Posts:
    1,065
    What are you trying to do?
     
  3. IchBinJager

    IchBinJager

    Joined:
    Dec 23, 2014
    Posts:
    127
    I'm trying to get a 2D object to move towards another, setting the transform down to be towards the enemy then using that to make them move towards it.
     
  4. Laperen

    Laperen

    Joined:
    Feb 1, 2016
    Posts:
    1,065
    Transform.up is the up vector relative to the transform's rotation, so it's not really pointing towards any specific target. Haven't seen how you are rotating the object or if you even are, so I don't know if that's where the problem is instead.

    If it's warping as you say, maybe the velocity has been set too high for the size of your game world. Another possibility is that transform.up is changing constantly because it's being rotated by physics while hitting surfaces and having friction affect it.
     
  5. IchBinJager

    IchBinJager

    Joined:
    Dec 23, 2014
    Posts:
    127
    transform.up = transform.position - Active_Ply.transform.position; I have this line before I set the velocity.
     
  6. Laperen

    Laperen

    Joined:
    Feb 1, 2016
    Posts:
    1,065
    Never tried changing the transform like that before. Is the rotation changing as you expect it to?

    In any case, with your newly provided line, I'd rather affect the velocity like this:
    Code (CSharp):
    1. Vector3 temp = transform.position - Active_Ply.transform.position;
    2. RBody.velocity = new Vector2(-temp.x, -temp.y).normalized * 2;
    and affect rotation separately. This way the rotation of the object will not affect the direction of travel, and at the very least eliminate it as a cause for your problem if you still encounter it..
     
  7. IchBinJager

    IchBinJager

    Joined:
    Dec 23, 2014
    Posts:
    127
    I will try that. Thanks. They do actually face the player cleanly, but the rather strange teleporting happens.