Smallest difference between two angles?

Viewed 8571

I'm trying to calculate the smallest difference between two angles.

This is my current code (a slight variation of something I found online):

float a1 = MathHelper.ToDegrees(Rot);
float a2 = MathHelper.ToDegrees(m_fTargetRot);

float dif = (float)(Math.Abs(a1 - a2);

if (dif > 180)
  dif = 360 - dif;

dif = MathHelper.ToRadians(dif);

It works fine except for in cases at the edge of a circle. For example if the current angle is 355 and the target angle is 5 it calculates the difference is -350 rather than 10 since 365 degrees is equal to 5 degrees.

Any ideas on what I can do to make this work?

4 Answers
Related