Reputation: 101
I have 2 objects in a game, an enemy and a player, and the enemy rotates toward the angle that points towards the player. The problem is that when the player crosses over the line at 0 degrees, the target angle changes from positive to negative, causing the enemy to turn all the way around instead of turning the few degrees it should in the opposite direction. Here is my code:
l.velX=-Math.cos(Math.toRadians(l.angle));
l.velY=-Math.sin(Math.toRadians(l.angle));
m.x+=l.velX;
m.y+=l.velY;
if(Math.toRadians(l.angle)<Math.atan2((m.y-p.y),(m.x-p.x)))
l.angle+=i.gameSpeed;
else l.angle-=i.gameSpeed;
Here's a crudely drawn diagram of what's happening:
How do I fix this?
Upvotes: 1
Views: 65
Reputation: 13195
Use the signum of the z component of the cross product:
l.angle+=Math.signum(l.velX*(p.y-m.y)-l.velY*(p.x-m.x))*i.gameSpeed;
(if it turns towards the wrong direction, use -=
, I have not really thought it through)
Upvotes: 3