gpt4 book ai didi

javascript - 从度数中获取方向

转载 作者:行者123 更新时间:2023-11-30 14:47:01 26 4
gpt4 key购买 nike

我构建了一个能够计算设备航向的小型指南针项目。所以我得到的是一个函数,它返回当前航向的 0° 和 360° 之间的值。

我想从这样的数组中获取当前航向方向的匹配值:(["North", "North-East", "East", "South-East", "South ", "西南", "西", "西北"])

img

(请记住:北 = 0°/359°)


但是我不知道如何得到这样的结果,下面这几行是我到目前为止得到的所有结果,但它似乎不起作用:

var directions = ["North", "North-East", "East", "South-East", "South", "South-West", "West", "North-West"]

function getDirection(heading) {
var index = Math.round((heading/8)/5,625)
return directions[index]
}

任何帮助将不胜感激,在此先感谢。

最佳答案

此解决方案应考虑所有可能的情况:

var index = Math.round(((angle %= 360) < 0 ? angle + 360 : angle) / 45) % 8;

function getDirection(angle) {
var directions = ['North', 'North-East', 'East', 'South-East', 'South', 'South-West', 'West', 'North-West'];
var index = Math.round(((angle %= 360) < 0 ? angle + 360 : angle) / 45) % 8;
return directions[index];
}

console.log( getDirection(0) );
console.log( getDirection(45) );
console.log( getDirection(180) );
console.log( getDirection(99) );
console.log( getDirection(275) );
console.log( getDirection(-120) );
console.log( getDirection(587) );

关于javascript - 从度数中获取方向,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48750528/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com