Struggling with 2Pi and 0

I hope I can explain this in a way someone will understand. I have a 2D physics world where sprites roam around chasing a moving points. The world also revolves around the central point of the client window. I have this working perfectly apart from one small calculation which makes a right mess of things.

If the sprite’s rotation is near 0 or 2Pi Radians, (0-360 degrees) the steering mechanism falls down.

To choose the direction to turn I’m using some simple calculations.

If Sprite.DesiredAngle > Sprite.Rotation Then Sprite.TurnValue = 0.02
If Sprite.Rotation > Sprite.DesiredAngle Then Sprite.TurnValue = -0.02

If MathHelper.ToDegrees(Sprite.Rotation) - MathHelper.ToDegrees(Sprite.DesiredAngle) > 180 Then Sprite.TurnValue = 0.02
If MathHelper.ToDegrees(Sprite.DesiredAngle) - MathHelper.ToDegrees(Sprite.DesiredAngle) > 180 Then Sprite.TurnValue = -0.02

Which all works fine, until the sprite is chasing it’s target with a rotation near the 2Pi / 0 radians point. It somehow falls apart and the sprite starts running off in a semi circular shape downwards (screen orientation).

I’ve tried working the calculations in several ways, but the outcome has to be the same. I can’t help thinking the calculations I’m using at the moment are far from elegant. It should really be nested in “if’s” but it’s like this at the moment to make it clearer what’s going on.

Has anyone else struggled with the same kind of thing? Or is there a better way to make the turning decision?


EDIT I’m sorry the code isn’t in a block, no matter what I try I can’t make the code insert work properly.

I fixed it for you. If you edit you’ll see how it works.

Thanks Tom, every time I paste code into the highlighted code marker it mixes things up.

For anyone who’s interested the answer is to do it correctly!

Dim b As Single = sprite.DesiredAngle - sprite.Rotation If b < 0 Then b += MathHelper.TwoPi If b < Math.PI Then sprite.TurnValue = 0.02 Else sprite.TurnValue = -0.02

There. Much more elegant. I actually worked this out by cutting out two card disks, pinning them to my table and revolving them round and round!