For beginners like me, the other answers - though very likely to give you a good result - were a bit difficult to understand what is going on. Therefore, here is my method that checks which direction (clockwise or counter-clockwise) is shortest between a cp(current point) and a tp(target point). It also assigns that shortest distance value to a shortestDistance variable. Based on what I specifically needed this method for, it was important for me to return a boolean value as to whether the shortest distance was in the clockwise or counter-clockwise direction. Here is the method:
public boolean checkIfClockwiseIsShortest(int cp, int tp) {
boolean clockwiseIsShortest = false;
if (cp != tp) { // if current point and target point are not the same...
if (tp > cp) { // if current point is less than target point AND..
if ((tp - cp) <= ((360 - tp) + cp)) {
clockwiseIsShortest = true;
shortestDistance = (tp-cp);
System.out.println("Case A: " + shortestDistance +" degrees clockwise");//[CAN REMOVE]
} else if ((tp - cp) > ((360 - tp) + cp)) {
clockwiseIsShortest = false;
shortestDistance = ((360 - tp) + cp);
System.out.println("Case B: " + shortestDistance+" degrees counter-clockwise");//[CAN REMOVE]
}
} else { // BUT if target point < current point
if ((cp - tp) <= ((360 - cp) + tp)) {
clockwiseIsShortest = false;
shortestDistance = (cp-tp);
System.out.println("Case C: " + shortestDistance+" degrees counter-clockwise");//[CAN REMOVE]
} else if ((cp - tp) > ((360 - cp) + tp)) {
clockwiseIsShortest = true;
shortestDistance = ((360 - cp) + tp);
System.out.println("Case D: " + shortestDistance+" degrees clockwise");//[CAN REMOVE]
}
}
}
return clockwiseIsShortest;
}
Note that cp is the starting point in integer degrees and tp is the target point in integer degrees; the type can be changed to double for more precision .
It does account for going (counter)clockwise past 0 degree mark.
The 3 if's it checks:
- is the starting/current point (cp) equal to target point(tp)? if so, no distance is given.
- if not equal, is the target point > current point in degrees OR is target point < current point in degrees?
- Based on this, the last if in the nest checks if going clockwise is less degrees that going counter-clockwise (or vise versa).
Again, the other posts with shorter code may work just fine.
Edit: BTW, the shortestDistance variable is a class variable, initialized within the same class as this method; if you are ripping this code, make sure that your class in which you are placing it also has a shortestDistance variable based on the primitive type as the cp and tp variables (or cast it).
abs(deg1 - deg2)
will give you the difference, and then some simple modulo math to make it be < 180 at all times should do the trick. – Acedia