Search Unity

  1. Megacity Metro Demo now available. Download now.
    Dismiss Notice
  2. Unity support for visionOS is now available. Learn more in our blog post.
    Dismiss Notice

Problems with movement

Discussion in 'Getting Started' started by tristanwheeler, Jan 16, 2016.

  1. tristanwheeler

    tristanwheeler

    Joined:
    Jan 11, 2016
    Posts:
    2
    I'm making a 2D game in which the player sprite follows the mouse. My code finds the velocity of the player and uses Atan2 to rotate the player in the direction of its movement.

    Code (CSharp):
    1. velocityX = transform.position.x - previous.x;
    2. velocityY = transform.position.y - previous.y;
    3. previous = transform.position;
    4. angle = (Mathf.Atan2(velocityX,velocityY)) * Mathf.Rad2Deg;
    Sometimes before the player comes to a halt, my velocityX or velocityY variable will briefly fluctuate between a much higher integer and fluctuate between positive and negative values. Can anyone help me figure out what is causing this glitch?
     
  2. JoeStrout

    JoeStrout

    Joined:
    Jan 14, 2011
    Posts:
    9,859
    It probably happens when your velocityY is zero, or very close to it. You should simply check if (transform.position - previous).magnitude is less than 1f or so, and not change your angle in that case (moving too slow for it to matter).