Created
May 11, 2023 14:30
-
-
Save shamrin/c623f0cf83ab79e4d90ffcc4a6fee480 to your computer and use it in GitHub Desktop.
Angle math functions in JavaScript
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
/** | |
* `n` modulo `d` (because JavaScript `%` remainder operator is useless when `n < 0`) | |
* @see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Remainder | |
* @param {number} n | |
* @param {number} d | |
*/ | |
export function mod(n, d) { | |
return ((n % d) + d) % d | |
} | |
/** | |
* Smallest equivalent angle, from -π to +π | |
* @param {number} angle | |
*/ | |
export function equivalentAngle(angle) { | |
return mod(angle + Math.PI, Math.PI * 2) - Math.PI | |
} | |
/** | |
* Same as `to`, but closest to `from` (can be used to prevent over-rotation) | |
* @param {number} from | |
* @param {number} to | |
*/ | |
export function closestAngle(from, to) { | |
return from + equivalentAngle(to - from) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment