The smallest difference between two angles?

I am trying to calculate the smallest difference between two angles.

This is my current code (a slight change to what 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 great, except at the edge of the circle. For example, if the current angle is 355 and the target angle is 5, it calculates the difference at -350, not 10, since 365 degrees is 5 degrees.

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

+5
source share
4 answers

You basically had it. Just take the diff module 360 ​​before checking to see if it will be more than 180:

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

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

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

dif = MathHelper.ToRadians(dif);

: @ , MathHelper.WrapAngle, :

diff = Math.Abs(MathHelper.WrapAngle(a2 - a1));
+7

:

if (dif < 0) dif = dif + 360;
if (dif > 180) dif = 360 - dif;
+3

, 0 <= theta < 360:

while(theta < 0) { theta += 360; }

():

const Double TwoPi = 2 * Math.Pi;
while(theta < 0) { theta += TwoPi; }
+1

case. ( ) :

vec(a) . vec(b) = ||a|| ||b|| cos(theta)

a b , ||a|| == ||b|| == 1.

vec(x) = [cos(x),sin(x)], :

unsigned_angle_theta(a,b) = acos(cos(a)cos(b) + sin(a)sin(b))

(n.b. )

+1

All Articles