Skip to content

Instantly share code, notes, and snippets.

@yomotsu
Last active May 11, 2023 14:53
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save yomotsu/165ba9ee0dc991cb6db5 to your computer and use it in GitHub Desktop.
Save yomotsu/165ba9ee0dc991cb6db5 to your computer and use it in GitHub Desktop.
Calculates the shortest difference between two given angles given in radians, in JS
// http://docs.unity3d.com/ja/current/ScriptReference/Mathf.DeltaAngle.html
var getDeltaAngle = function () {
var TAU = 2 * Math.PI;
var mod = function ( a, n ) { return ( a % n + n ) % n; }
return function ( current, target ) {
var a = mod( ( current - target ), TAU );
var b = mod( ( target - current ), TAU );
return a < b ? -a : b;
}
}();
getDeltaAngle( 0, Math.PI );
@shamrin
Copy link

shamrin commented May 11, 2023

Slightly clearer version (in my opinion):

var getDeltaAngle = function () {
  var TAU = 2 * Math.PI;
  var mod = function (a, n) { return ( a % n + n ) % n; } // modulo
  var equivalent = function (a) { return mod(a + Math.PI, TAU) - Math.PI } // [-π, +π]
  return function (current, target) {
    return equivalent(target - current);
  }
}();

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment