# Angle Math rotates wrong way when passing origin

I am developing a Missile class in VB.NET that tracks its target. It is given a Target (as a Vector2, aka a point), a velocity and a rotation rate (radians per second). Every time its Update() method is called, it calculates its next position and the angle it must now face in the following way:

1) Move forward by Velocity * Elapsed in direction CurrentAngle (elapsed is the time elapsed since the last update call)
2) Calculate the Target Angle (which way the missile wants to face) using Atan2
3) Check if the difference between the two angles is more than RotationRate * Elapsed. If not, just set CurrentAngle = TargetAngle and skip the rest.
4) If TargetAngle > CurrentAngle, then add RotationRate * Elapsed to angle, else subtract RotationRate * Elapsed from it.

The problem is that when the correct rotation path goes through the origin (angle goes from Pi*2 to 0) it rotates back the wrong way. I've tried lots of ways to fix this and spent hours debugging but I just can't get it to work. Could someone sort this bug out for me?

Burningmace
``````position += new Vector2((float)Math.Sin(CurrentAngle) * Velocity * Elapsed, (float)Math.Cos(CurrentAngle) * Velocity * Elapsed);

float TargetAngle = (float)(Math.PI) - (float)Math.Atan2(target.Y - position.Y, target.X - position.X);
if (target.X == position.X)
{
TargetAngle = (float)(Math.PI * 0.75f);
}
if (target.Y == position.Y)
{
TargetAngle = 0;
}

float angleDelta = Math.Abs(CurrentAngle - TargetAngle);

if (angleDelta >= RotationSpeed * Elapsed)
{
// We need to cap to RotationSpeed
if (AngleDirection(CurrentAngle,TargetAngle))
{
CurrentAngle += RotationSpeed * Elapsed;
}
else
{
CurrentAngle -= RotationSpeed * Elapsed;
}
}
else
{
// We can rotate without limitation!
CurrentAngle = TargetAngle;
}
``````
Game ProgrammingMath / ScienceVisual Basic.NET

Last Comment
Christopher Kile

8/22/2022 - Mon