javascript - 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 mouse cursor. use above code calculate angle in radians , "animate" angle on few frames. however, when angle variable turns positive negative (at pi radians), turns clockwise way new cursor position (as seen in red). however, desired path go straight new angle (green arrow).

enter image description here

edit:

this came with, seems work. 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)); 

you have take account output of atan2 ever in range -pi +pi. if difference between output of atan2 , previous angle greater pi, know wraparound occurred, , have correct adding/subtracting 2*pi.


Comments

Popular posts from this blog

php - failed to open stream: HTTP request failed! HTTP/1.0 400 Bad Request -

java - How to filter a backspace keyboard input -

java - Show Soft Keyboard when EditText Appears -