Javascript 如何将角度和幅值转换为水平和垂直分量?
我需要在角度/幅值和水平/垂直分量之间进行转换 这些公式最接近于工作原理,但有点浮华:Javascript 如何将角度和幅值转换为水平和垂直分量?,javascript,Javascript,我需要在角度/幅值和水平/垂直分量之间进行转换 这些公式最接近于工作原理,但有点浮华: function velocityToSpeeds(direction, speed) { return { hspeed: -speed*Math.sin(Math.toRad(direction) - 90) + 0, vspeed: -speed*Math.cos(Math.toRad(direction) - 90) + 0 }; } function velocityTo
function velocityToSpeeds(direction, speed) {
return {
hspeed: -speed*Math.sin(Math.toRad(direction) - 90) + 0,
vspeed: -speed*Math.cos(Math.toRad(direction) - 90) + 0
};
}
function velocityToSpeedsALTERNATIVE(direction, speed) {
return {
x: speed*Math.cos(Math.toRad(direction)),
y: speed*Math.sin(Math.toRad(direction))
};
}
function speedsToVelocity(hspeed, vspeed) {
return {
direction: Math.round(Math.toDeg(Math.atan2(vspeed, hspeed))) + 0,
speed: Math.round(Math.sqrt(hspeed * hspeed + vspeed * vspeed)) + 0
}
}`
+0
用于停止函数返回-0
我使用屏幕坐标;e、 g.(0,0)位于左上角。此外,0度向右,270度向下。因此,如果我将水平速度(hspeed)1和垂直速度(vspeed)0转换为角度和大小,我应该得到0度(方向),1大小(速度)
speedsToVelocity(1,0)
工作正常
但是speedsToVelocity(0,1)
返回90度,当角度应为270度时返回1个速度
这些公式还有其他问题,但它们是我所掌握的最好的。请不要向我指出任何其他问题/答案;我向你保证,如果它存在于互联网上,我已经尝试过了,发现它也不起作用。在过去的3天里,我已经建立了相当多的向量函数集,这些函数应该可以完成我需要的工作,但没有任何效果。我最终通过这些修改使它能够工作:
function velocityToSpeeds(direction, speed) {
return {
hspeed: Number(-Number(speed)*Math.sin(Math.toRad(Number(direction) - 90))) + 0,
vspeed: Number(-Number(speed)*Math.cos(Math.toRad(Number(direction) - 90))) + 0
};
}
function speedsToVelocity(hspeed, vspeed) {
return {
direction: Math.round(Number(Math.toDeg(Math.atan2(Number(vspeed), Number(hspeed))))) + 0,
speed: Math.round(Number(Math.sqrt(Number(hspeed) * Number(hspeed) + Number(vspeed) * Number(vspeed)))) + 0
}
}
以下是额外奖励:
function negativeHspeed(direction) {
return ((180 - direction) + 360) % 360;
}
function negativeVspeed(direction) {
return 360 - direction;
}
为什么你所有的函数都是密集的、不可读的、神奇的单行线?他们甚至还没开始工作,这是一道数学题。用名字写出你的变量和常量。你需要多少线就拿多少线。使用
console.log
或调试器输出每个操作的结果。在某个步骤中,您将得到意外的结果。这就是你公式中的错误。@AndrewKoster我忘了删除调试时插入的所有可能多余的Number()
。