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

I struggle with this in JavaScript, but this problem applies to many other languages ​​/ environments.

I want one object to rotate in the direction of another object, and I use:

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

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

In KineticJS, the JS / HTML5 / Canvas programming environment that I use, the angle is specified in radians from 0 to 2 pi, starting from the positive Y axis and going clockwise. This behavior is also observed in many other programming environments.

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

To clarify:

Difference between normal radians and atan2 ()

Question:

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

+4
source share
3 answers

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

+2
source

In both cases, the values ​​are the same, modulo 2*PI and configured for different agreements on signs and offsets. 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 
+2
source

If your result is between 0 and Pi, the result is pretty straight forward. If your result is between -Pi and 0, add 2 * Pi to your result, so you get the result in the interval 0, 2 * Pi.

Of course, it would be nice if you implemented a separate function for this type of conversion so as not to duplicate your code from time to time.

+1
source

Source: https://habr.com/ru/post/1490745/


All Articles