How to reverse a reading of degrees

Hey guys,

I’m working on a top down 2D space sim, and I’ve just run into a problem I didn’t expect.

In my game, when the spaceship turns, the heading in degrees changes accordingly (north is 0, south is 180, etc). When I was doing this in 3D, it worked like a charm. All I had to do was calculate the heading using the following line of code:

heading = transform.eulerAngles.y;

But now that I’m working in 2D, with the Z axis pointing “downward”, the heading DECREASES when the ship turns clockwise when what I need it to do is INCREASE, and vice versa when it turns counter clockwise.

Is there some type of formula or mathf function that can change the value to what I need it to be? I’m struggling to find a solution to this, and I’m hoping someone out there knows of one. Thanks in advance.

The usual mathematical definition of an angle does increase in the counter clockwise direction, starting at 0 on the right (or “east” if you will). This is how all of trigonometry works.

I would generally recommend to not use eulerAngles. They suffer from gimbal lock and Unity uses quaternions internally to represent rotations. Though if you want you can use whatever you want.

If your angle has already the right offset (so 0 is where you want 0 to be), you can simply inverse the value:

heading = -transform.eulerAngles.z;

Depending on the range you want to use (0 to 360 or -180 to 180) you might need to perform a proper roll over. For the range 0 to 360 you have to do

if (heading < 0)
    heading += 360;
if (heading > 360)
    heading -= 360;

for the range -180 to 360 you have to do

if (heading < -180)
    heading += 360;
if (heading > 180)
    heading -= 360;

Instead of eulerAngles you might want to use Vector3.SignedAngle with a direction vector of your object. Note that SignedAngle always return a value between -180 and 180. If you want 0 to 360 just use

if (heading < 0)
    heading += 360;

I figured it out. For anyone who is having the same issue, here is the solution that worked for me:

heading = Mathf.Repeat(-transform.eulerAngles.z, 360f);

Credit goes to EmmaEwert in the Unity Forums for giving me this excellent solution.