Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Returns the difference of two angles given in radians. The result is always between -PI and PI.
// 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