- Home /
Velocity to 2D rotation (angle from velocity vector with atan2)
Im working on a side scroller game. I have projectiles that have velocity, but don't have an angle, while the particles attached to those projectiles need it to rotate properly (on the z-axis)
I've seen people recommend Mathf.Atan2, but when I use it the particles only rotate properly when both x and y are either positive or negative (and even then it goes in the wrong direction when getting close to the axes), so:
when I shoot a projectile upwards, particles' rotation is around 0 (perpendicular, aiming to the right)
when its to the left, the particles are aiming down
when shooting down, the particles aim to the left
when shooting right, the particles aim upwards
here's the code:
private void ControlDirection ( Vector3 direction )
{
float angle = Mathf.Atan2( direction.x , direction.y ) * Mathf.Rad2Deg;
transform.rotation = Quaternion.AngleAxis( angle , Vector3.forward );
}
Answer by andrew-lukasik · Jun 25, 2021 at 01:35 PM
it's Atan2( Y , X )
float angle = Mathf.Atan2( direction.y , direction.x ) * Mathf.Rad2Deg;
Then, either:
transform.rotation = Quaternion.AngleAxis( angle , Vector3.forward );
or:
transform.rotation = Quaternion.Euler( 0 , 0 , angle );
You missed the point, partner. You have Atan2(x,y)
where it should be Atan2(y,x)
. Symptoms you describe match perfectly what one can expect from confusing these two parameters with each other.