Angular 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);


The object points to my mouse cursor. I use the above code to calculate the angle in radians and animate the angle by a few frames. However, when the variable angle

turns from positive to negative (in PI radians), it rotates clockwise to the new cursor position (as seen in red). However, my desired path is to go straight to the new corner (green arrow).

enter image description here


This is what I ran into, it seems to work. Can 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));



source to share

1 answer

You should keep in mind that atan2's output is always only in the -pi to + pi range. If the difference between the output of atan2 and your previous angle is greater than pi, then you know that some traversal has occurred and you need to fix it by adding / subtracting 2 * pi.



All Articles