我有下面的函数从三个点返回我的弧度角度,编码如下:
function pointsToAngles(x1, y1, x2, y2, cpx, cpy) {
const r1 = Math.atan((y1 - cpy)/(x1 - cpx));
const r2 = Math.atan((y2 - cpy)/(x2 - cpx));
return [r1, r2];
}
我知道
atan()
因为它应该返回 -pi/2
到 pi/2
范围内的结果,所以 JavaScript 提供 atan2()
返回 -pi
到 pi
范围。我想重写函数以使用 atan2,可能是:
function pointsToAngles(x1, y1, x2, y2, cpx, cpy) {
const r1 = Math.atan2((x1 - cpx), (y1 - cpy));
const r2 = Math.atan2((x2 - cpx), (y2 - cpy));
return [r1, r2];
}
但是,
atan2
版本没有按预期工作。我得到的结果与 atan()
产生的结果不同,它不遵循我期望遵循的逻辑[不同之处在于 pi/2 或其他东西......].
看起来
atan()
版本运行正常,而atan2()
版本不正常。我错过了什么?我如何以类似于 atan() 的方式计算角度,仅返回大于 pi/2 的角度?
看来您已经交换了 Math.atan2() 函数的参数。参数的正确顺序应该是 (y, x),而不是 (x, y) Math.atan2().