I'm working on a small maze puzzle game and I'm trying to add a compass to make it somewhat easier for the player to find their way around the maze. The problem is: I'm using XNA's draw method to rotate the arrow and I don't really know how to get it to rotate properly. What I need it to do is point towards the exit from the player's position, but I'm not sure how I can do that.

So does anyone know how I can do this? Is there a better way to do it?


1 Answer 1


The secret is atan2:

Vector2 exitPosition = whatever;
Vector2 currentPosition = whatever;

Vector2 direction = exitPosition - currentPosition;
float angle = (float)Math.Atan2(direction.Y, direction.X);

atan2 (MSDN) gives you the angle of a vector, with the positive X axis being at an angle of zero, and moving in the positive direction towards the positive Y axis (which is π/2). Simply pass this as the rotation parameter to SpriteBatch.Draw (MSDN).

Make sure your compass needle texture is pointed the correct way for an angle of zero (ie: to the left), or add an appropriate angular offset in your code. Set the origin parameter of the SpriteBatch.Draw call to the pivot point of your needle texture.


You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .