How can I obtain the angle from the x and y speed?

I have the x and y speed in a vector2
How can I get the angle of the direction of the object with those 2 values?

You use Mathf.Atan2.

1 Like

Thanks

I tried to use

void Update () {

          //this is the movement
            transform.position += new Vector3 (speed.x * Time.deltaTime, speed.y * Time.deltaTime, 0);


            transform.Rotate(0, 0, Mathf.Atan2(speed.x, speed.y) * Mathf.Rad2Deg);

   //this is gravity
            speed -= new Vector2 (0, gravity * Time.deltaTime);
        }

But it rotates in really weird angles.
One frame its one random angle and in the next is another random angle.

You need to read those Atan2 docs more carefully. :wink: The first parameter is y, and the second parameter is x; this is opposite what you might expect.

Also, I don’t think it makes much sense to call Rotate every frame. Just because the speed indicates a heading that’s, say, 90 degrees away from the original direction, doesn’t mean you want to rotate an additional 90 degrees each frame, right?

I think what you probably want instead is something like:

transform.rotation = Quaternion.Euler(0, 0, Mathf.Atan2(speed.y, speed.x) * Mathf.Rad2Deg);

Good luck,

  • Joe
1 Like

I really didnt expect transform.Rotate to be relative.

Edit: Everything is working! Thanks!

–Stef

Unity’s pretty consistent in their naming. Rotate is a verb, so it does exactly that: it rotates the object by the amounts you specify.

If it were a method to set the rotation, they’d probably call it SetRotation.

Glad you got it working!

  • Joe