Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angle animation with atan2

var diffx = (this.destination.x - pos.x), px = diffx / dist;
var diffy = (this.destination.y - pos.y), py = diffy / dist;
var angle = Math.atan2(diffy, diffx) - rot.z;

rot.set(0, 0, rot.z + angle / 24);

An object points towards my mouse cursor. I use the above code to calculate the angle in radians and "animate" the angle over a few frames. However, when the angle variable turns from positive to negative (at PI radians), it turns clockwise all the way to the new cursor position (as seen in red). However, my desired path is to go straight to the new angle (green arrow).

enter image description here

EDIT:

This is what I came up with, seems to work. Could I improve?

            if(atan - this.lastAtan < -Math.PI)
                atan += Math.PI * 2;
            else if(atan - this.lastAtan > Math.PI)
                atan -= Math.PI * 2;
            this.lastAtan = atan;

            var zrot = rot.z + (atan * 12 * Game.dt);
            rot.set(0, 0, zrot % (Math.PI * 2));
like image 353
John Avatar asked Jun 27 '26 05:06

John


1 Answers

You have to take into account that the output of atan2 is only ever in the range -pi to +pi. If the difference between the output of atan2 and your previous angle is greater than pi, then you know that some wraparound occurred, and you have to correct for it by adding/subtracting 2*pi.

like image 53
Jack Whitham Avatar answered Jun 28 '26 19:06

Jack Whitham



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!