Skip to content

Instantly share code, notes, and snippets.

@shamrin
Created May 11, 2023 14:30
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save shamrin/c623f0cf83ab79e4d90ffcc4a6fee480 to your computer and use it in GitHub Desktop.
Save shamrin/c623f0cf83ab79e4d90ffcc4a6fee480 to your computer and use it in GitHub Desktop.
Angle math functions in JavaScript
/**
* `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