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).
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
Post a Comment