Comparing angles and working out the difference

Posted by Thomas O on Game Development See other posts from Game Development or by Thomas O
Published on 2010-10-13T12:08:26Z Indexed on 2011/11/17 2:05 UTC
Read the original article Hit count: 299

Filed under:
|

I want to compare angles and get an idea of the distance between them. For this application, I'm working in degrees, but it would also work for radians and grads. The problem with angles is that they depend on modular arithmetic, i.e. 0-360 degrees.

Say one angle is at 15 degrees and one is at 45. The difference is 30 degrees, and the 45 degree angle is greater than the 15 degree one.

But, this breaks down when you have, say, 345 degrees and 30 degrees. Although they compare properly, the difference between them is 315 degrees instead of the correct 45 degrees.

How can I solve this? I could write algorithmic code:

if(angle1 > angle2) delta_theta = 360 - angle2 - angle1;
else delta_theta = angle2 - angle1;

But I'd prefer a solution that avoids compares/branches, and relies entirely on arithmetic.

© Game Development or respective owner

Related posts about math

Related posts about angles