I'm trying to make a method in Java that will be able to calculate the difference between two angles. This might be a topic for game programming but I think its rather general and I don't think this topic would land in any specific category since calculating angles has many uses.

I have a control angle, and I'm supposed to find the angle closest (or with the least difference) to the control angle. The angle in this case is the angle between one point and another object. So basically all I need to do is calculate the difference between one angle and another.

I have a method that can get an angle between two points and returns the angle between the values -180 , 180 with 0 being the right-most point as shown in the top of the picture above.

The main problem is that the difference has to be less than or equal to 180. If the control angle is in quadrant I and the angle is in quadrant IV then its easy because then the difference is equal to control angle - angle. Vice versa if they traded quadrants.

But then what would happen if the situation in the bottom portion of the picture happened? I could say the difference is control angle - angle - 180. That would surely work. But the problem is, the way this is turning out, its one massive if-else block. What I'm looking for is a discussion on how to come up with one equation/algorithm that will be able to effectively calculate the difference between two angles without a massive if-else block.

What I have so far in terms of code is:

public static double differenceAngle(double theta1, double theta2) { double dif = theta2 - theta1; while( dif < -PI) dif+=2*PI; while( dif > PI) dif-=2*PI; if(dif < 0) dif *=-1; dif*=180.0/PI; return dif; }

theta1 and theta2 are double variables expressed in radians, and upon returning, its converted back to degrees

This post has been edited by **HunterE30633**: 21 March 2010 - 10:54 PM