I need to get the shortest direction between two angles. Like if Ang1 is 5 and Ang2 is 355 then I want it to return that I need to subtract from Ang1 to get to Ang2 .
I have some code that will tell me the shortest distance, but not the shortest direction.
function getShortAngle(a1, a2) {
let angle = (Math.abs(a1 - a2))%360;
if(angle > 180)
angle = 360 - angle;
return angle;
};
console.log(getShortAngle(360, 720));
Or in Smallbasic:
Sub GetShortestpath
angle = Math.Remainder((Math.abs(a1 - a2)),360)
if angle > 180 Then
angle = 360 - angle
EndIf
Return = angle
EndSub
Thanks for any help!
Surely that's just setting the direction based on which angle you choose.
If you're working out the angle/direction from
a1
toa2
, the following pseudo-code should give you what you need:In cases where the difference is exactly 180°, it prefers the clockwise direction.
Forgive the complex expression getting the angle, it just to ensure you get a value 0 through 359 regardless of the relative positions and workings of your modulo operator with negative numbers.
You can greately simplify it if you make the precondition more restrictive, ensuring
a1
anda2
are limited to the range0..359
: