javascriptmathrotationdistance

Calculate absolute distance of two rotation degrees, as a number (in JavaScript)


I would like to calculate the distance between two degree values. I know that I could use this if the points just where on one axis:

var dist = Math.abs( x1 - x2 );

...but the problem with degrees is, that they can either be negative or positive, also they could be somewhere above 360. My goal is to calculate the distance, no matter if the rotation is negative or higher then 360°

EDIT

To make it clearer what I want: For example, I could could have the values -90deg and 270deg. This should result in a result of 0 for the distance. If the first element's rotation would change to either -100deg of -80deg, the distance should change to 10.


Solution

  • If you want this to work for any angle (including angles like 750 deg) and in a language where you have a remainder operator that's signed (like Java or JavaScript), then you need to do more work. If you're in a language with an unsigned operator, then the answer by Rory Daulton is good. (That is, in summary, use rot1%360 below where I call modulo(rot1,360) and similarly for rot2.)

    First you need to make each negative angle into an equivalent positive angle. There's no single operator that will do this since, for example, -10 % 360 = -10 in these languages. You can get this with a function like this (assuming y is positive):

    function modulo(x,y) {
        var xPrime = x;
        while(xPrime<0) {
            xPrime += y; // ASSUMES y > 0
        }
        return xPrime % y;
    }
    

    Then you can do more or less as suggested by others, but using this custom function instead of the % operator.

    var distance = Math.abs(modulo(rot1,360) - modulo(rot2,360))
    distance = Math.min(distance, 360-distance)