比较两个罗盘轴承

时间:2014-02-28 11:00:04

标签: javascript jquery

我有两个罗盘轴承(0-360度):

var routeDirection = 28
var windDirection = 289

我需要比较这些方位以确定骑手是否会得到

a)横风

b)尾风

c)头风

我尝试将轴承转换为指南针方向,例如:

  var compass = ['N', 'NNE', 'NE', 'ENE', 'E', 'ESE', 'SE', 'SSE', 'S', 'SSW', 'SW', 'WSW', 'W', 'WNW', 'NW', 'NNW', 'N'];
  var windDirection = compass[Math.round(bearing / 22.5)];

然后进行基本的字符串比较:

if (routeDirection=='N') && (windDirection=='S') {
 output = 'Headwind'
}

但显然这是冗长而低效的......

2 个答案:

答案 0 :(得分:1)

假设你正在直接上升,你就有了这个:

\ Head wind /
 \         /
  \       /
   \  |  /
    \ | /
Cross\|/Winds
     / \
    /   \
   /     \
  /       \
 /         \
/ Tail wind \

所以基本上......首先你转动你的视角,这样你就可以在0号轴上旅行:

var adjustedWindDirection = windDirection - routeDirection;

当然,轴承应该在0-360范围内,所以再次调整:

adjustedWindDirection = (adjustedWindDirection+360)%360;

现在我们需要找出方向所在的象限:

var quadrant = Math.round((adjustedWindDirection-45)/90);

最后:

var winds = ["head","cross (left)","tail","cross (right)"];
var resultingWind = winds[quadrant];

完成!

答案 1 :(得分:1)

我会直接比较路线方向和风向,并根据差异确定风的类型:

if(routeDirection > windDirection)
    var difference = routeDirection - windDirection;
else
    var difference = windDirection - routeDirection;

// left/right not important, so only need parallel (0) or antiparallel (180)
difference = difference - 180;
//keep value positive for comparison check
if(difference < 0)
    difference = difference * -1;

if(difference <= 45) // wind going in roughly the same direction, up to you and your requirements
    output = "headwind";
elseif(difference <= 135) // cross wind
    output = "crosswind";
elseif (difference <= 180)
    output = "tailwind";
else
    output = "something has gone wrong with the calculation...";

上述计算意味着您没有对每个罗盘点进行比较,只对船头和风的相对差异进行比较,从而减少了冗长度。它还允许通过使用较小程度的步骤和添加更多的elseif来进行多角度比较。这也可以通过switch()完成,但会出现类似的代码行数。