I'm making a javascript game in which I want enemy ships to be able to rotate towards a specified point. Their movement can then be calculated from their angle. The following code for the rotation works only if the ship is below and to the right of its target. If the ship is to the left, it rotates to ~0 degrees and jitters there. To the top right it continuously rotates counterclockwise. What the heck am I doing wrong here? Any suggestions as to a better method?
obj.angle %= 360;
// Calculate angle to target point
var targetAngle = Math.atan2(obj.mode.dest.y - obj.y, obj.mode.dest.x - obj.x) * (180 / Math.PI) + 90;
// Get the difference between the current angle and the target angle
var netAngle = Math.abs(obj.angle - targetAngle) % 360;
// Turn in the closest direction to the target
netAngle > 180 ? obj.angle += obj.shipType.turnSpeed : obj.angle -= obj.shipType.turnSpeed;
if(obj.angle < 0) obj.angle += 360;
if(obj.angle > 360) obj.angle -= 360;
My question is very similar to this one, which explains it better but unfortunately is in C#.
EDIT: Here's the working code, for anyone who might find it useful:
obj.angle %= 360;
var targetAngle = Math.atan2(obj.mode.dest.y - obj.y, obj.mode.dest.x - obj.x) * (180 / Math.PI) + 90;
targetAngle = (targetAngle + 360) % 360;
if(obj.angle != targetAngle)
{
var netAngle = (obj.angle - targetAngle + 360) % 360;
var delta = Math.min(Math.abs(netAngle - 360), netAngle, obj.shipType.turnSpeed);
var sign = (netAngle - 180) >= 0 ? 1 : -1;
obj.angle += sign * delta + 360;
obj.angle %= 360;
}