Created
May 5, 2019 07:50
-
-
Save bohnacker/966e2d766fee49c62a6f8a44aa03ba15 to your computer and use it in GitHub Desktop.
Returns the difference of two angles given in radians. The result is always between -PI and PI.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Returns the difference of two angles given in radians. | |
// The result is always between -PI and PI. | |
function angleDifference(angle1, angle2) { | |
const TWO_PI = Math.PI * 2; | |
let a1 = (angle1 % TWO_PI + TWO_PI) % TWO_PI; | |
let a2 = (angle2 % TWO_PI + TWO_PI) % TWO_PI; | |
if (a2 > a1) { | |
let d1 = a2 - a1; | |
let d2 = a1 + TWO_PI - a2; | |
if (d1 <= d2) { | |
return -d1; | |
} | |
else { | |
return d2; | |
} | |
} | |
else { | |
let d1 = a1 - a2; | |
let d2 = a2 + TWO_PI - a1; | |
if (d1 <= d2) { | |
return d1; | |
} | |
else { | |
return -d2; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment