Finding the closest difference between 2 degrees of a compass - Javascript

不问归期 提交于 2019-12-02 03:40:05
function GetHeadingDiff(_Heading1, _Heading2)
{   
    return (_Heading2-_Heading1+540) % 360 - 180;
}

Examples:

GetHeadingDiff( 280, 270 )
-10
GetHeadingDiff( 270, 280 )
10
GetHeadingDiff( 350, 20 )
30
GetHeadingDiff( 20, 350 )
-30

first of, why are you doing back and forth conversion of radians and degrees? look at this. http://jsfiddle.net/dTmPn/5/

var diff = _Heading2-_Heading1;
if(diff>180) diff-=360;
if(diff<-180) diff+=360;
return diff;

is that enough?

im not sure how you expect it to work, (which it doesnt i tried 10-30 and got 19.999996) but this would be the general idea based on your code.

sum1 = ConvertToDegrees((ConvertToRadians(_Heading2) - ConvertToRadians(_Heading1)));
sum2 = ConvertToDegrees((ConvertToRadians(_Heading1) - ConvertToRadians(_Heading2)));

return sum1 < sum2 ? sum1 : sum2;

this does you calculation twice in opposite directions and returns the smaller sum.

i would do it like this:

function GetHeadingDiff(s1, s2)
{  
    r1 = (s1 - s2 + 360 ) % 360;
    r2 = (s2 - s1 + 360 ) % 360;

    return r1<r2?r1:r2;
}

fiddle

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!