How to use atan2() in combination with other Radian angle systems

╄→尐↘猪︶ㄣ 提交于 2019-12-03 13:50:41

问题


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:

The question:

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


回答1:


If you want the angle to increase clockwise from 0 on the y axis, calculate the angle as atan2(x,y). This however give negative angles for x<0, so you should add 2*pi in this case.




回答2:


The values are the same in both cases, modulo 2*PI, and with an adjustment for the different sign and offset convention. Pseudo-code:

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



回答3:


If your result is between 0 and Pi, then the result is pretty straight-forward. If your result is between -Pi and 0, then add 2*Pi to your result, this way you will have your result in the interval of 0, 2*Pi.

Of course, it would be nice if you would implement a separate function for this type of conversion, to not duplicate your code every now and then.



来源:https://stackoverflow.com/questions/17574424/how-to-use-atan2-in-combination-with-other-radian-angle-systems

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!