6

I am struggling with this in JavaScript, but this problem applies to many other languages/environments as well.

I want to have one object rotating towards the position of another object, and I use:

atan2(obj1.dy, obj1.dx) - obj2.getRotation()

to check if the second object should rotate clockwise or counterclockwise at a given time.

In KineticJS, the JS/HTML5/Canvas programming environment I am using, the angle is specified in radians from 0 to 2 pi starting at the positive Y axis and going clockwise. This behaviour is seen in many other programming environments as well.

However, when calculating the angle of movement from the second object with the Math.atan2(y,x) function, the angle is specified from -pi to pi, starting at the positive X axis, going counterclockwise.

To clarify:

Difference between normal radians and atan2()

The question:

How can I calculate an angle in normal radians from the result of the atan2() function?

4

4 回答 4

3

两种情况下的值都是相同的,模数2*PI,并且针对不同的符号和偏移约定进行了调整。伪代码:

theta = 0.5*M_PI - atan2(y, x); // adjust for required sign/offset
theta = fmod(theta, 2.0*M_PI);  // make result modulo 2*PI
于 2013-07-10T15:19:11.973 回答
2

如果您希望角度从 y 轴上的 0 顺时针增加,请将角度计算为 atan2(x,y)。但是,对于 x<0,这会给出负角,因此在这种情况下您应该添加 2*pi。

于 2013-07-10T15:30:18.013 回答
1

如果您的结果介于 0 和 Pi 之间,那么结果非常简单。如果您的结果介于 -Pi 和 0 之间,则将 2*Pi 添加到您的结果中,这样您的结果将在 0、2*Pi 的区间内。

当然,如果您为这种类型的转换实现一个单独的函数,而不是时不时地重复您的代码,那就太好了。

于 2013-07-10T16:20:50.217 回答
0

只需使用条件

 var radians = Math.atan2(e.y - cy, e.x - cx);
 if(radians < 0 ) {radians += 2*Math.PI;}

var canvas = document.getElementById('canvas');
var ctx = canvas.getContext("2d");
canvas.onmousedown = function(e){
var rect = canvas.getBoundingClientRect();
var cx = rect.left + rect.width / 2, cy = rect.top + rect.height / 2;
var radians = Math.atan2(e.y - cy, e.x - cx);
if(radians < 0 ) {radians += 2*Math.PI;}
ctx.moveTo(cx,cy);
ctx.lineTo(cx + 100 * Math.cos(radians), cy + 100* Math.sin(radians));
ctx.stroke();
};
<canvas id="canvas" width="200px" height="200px" style="background-color: gold;"></canvas>

于 2020-02-22T20:01:34.937 回答