# Getting angle with Mathf.Atan2 problem

Hi guys, I have been having a problem retrieving an angle from a rigid body.

I am using this equation to get the SlipAngle from my car’s velocities.

``````private var car : Rigidbody;
var carVelocity : Vector3;
var degrees : float;

function Start () {
car = GetComponent.<Rigidbody>();
}

function Update () {
carVelocity = car.velocity;
degrees =  Mathf.Atan2(-carVelocity.z,-carVelocity.x ) *  180/Mathf.PI;
}
``````

The problem is if my car is rotated 270 degrees, then press play, the angle shows -180?
If i rotate the car 90 degrees, then press play, the angle is 90 to begin with.
With no lateral or longitudinal velocity???

I have a simple quad rotating with the degrees. It works great other than the fact its not 0 when it should be.

It’s either 90, 180 etc. Depending on my cars rotation when I press play.

Why does it show 90, -180 etc when my velocities are 0?

Thanks, Tim.

EDIT:

I changed it to this

``````degrees =  Mathf.Atan2(carVelocity.x,carVelocity.z) * 2 * 90/Mathf.PI  ;
``````

Debugging in scene view produces correct values.

I have a Gizmos.DrawRay pointing in the rigidbodys z velocity’s direction.
(Forwards).

When I press play I noticed the ray extends out on the x axis because my car is already rotated 90 degrees. Is this a bug or am I doing something wrong?

z velocity is always forwards right?

Assuming I know what you mean by slip angle, there are other ways of getting meaningful data of this nature. Here’s an example based off a signed angle method from my math library.

Untested, but it should return approximately zero if the vehicle is moving in the direction it is facing, 90 or -90 if it’s moving perpendicular to the direction its facing, and so on.

Let me know if this works and is what you were looking for. Otherwise, might want to tell us what you mean by slip angle.

``````Vector3 f = body.forward;
Vector3 v = body.velocity.normalized;
float s = Mathf.Atan2(
Vector3.Dot( Vector3.up, Vector3.Cross( f, v )),
Vector3.Dot( f, v ));

float slipAngle = s * Mathf.Rad2Deg;
``````

Replace Vector3.up with the normal of your world; up for 3d, forward for 2d