Every game requires objects to face other objects and it can be a perplexing problem the first time you tackled it. It’s been awhile now since I first looked into the subject, but I wanted to share my method with the world in hopes of two things. First, that it will help someone out trying to do this and secondly, maybe someone has a better/different way.
The final function that I’m going to create is actually pretty short and it takes in 2 arguments (both Vector2 positions) and returns the angle (in Radians) that the object would need to rotate to face the second object. First though, let’s look at a diagram of two objects.

Alright, so the green triangle is going to act as our object that we are rotating and the red circle is what we want it to look at. Feta is the resultant angle that will give us our rotation amount (in radians). Sides ‘a’ and ‘b’ are the values that we’ll use to calculate what that angle is by using Atan.
Now, let’s actually do it. First step is to get the values of ‘a’ and ‘b’. Pretty simple really.
double a = pos2.X - pos1.X;
double b = pos2.Y - pos1.Y;
Easy enough. It’s important to note that if we rotate this image 90 degrees ‘b’ becomes X distance and ‘a’ becomes Y distance. But we aren’t going to worry about this, there is a simple check I use in my function that accounts for this sort of thing happening. Next step is to calculate the atan.
double feta = Math.atan(a / b);
Yup, that’s it. That is our resultant angle right there. Now, I work mainly with XNA when I do game programming stuff, so if you are working with another language your syntax to call atan may be different. Just something to keep in mind.
Now we need to do that check that I had mentioned before in case our object we’re looking at is below the object that is doing the looking, this check will fix it.
if (pos2.Y < pos1.Y)
{
feta += MathHelper.ToRadians(180);
}
We just add on 180 degrees to our rotation. This also covers the fact that if you mirror the image that I posted up at the beginning it will give you the same angle as the orientation it is now, however, the object would need to be rotated the opposite amount. Once again, if you aren’t using XNA you may not have the wonderful ‘MathHelper’ available. Luckily though it’s a simple conversion. 1 Radian = pi/180 degrees! So you could make your own function like this:
public float degreesToRadians(double degrees)
{
return degrees * (pi / 180);
}
Well that’s really all it takes. I’m going to post my final function here, but first I want to note that the first 2 steps I combined into 1 just to save having to make the variables for ‘a’ and ‘b’. Also, it’s important that the first parameter is the position of the object you want to rotate, and the second parameter is where you want it to look at. That’s it!
public double getAngle(Vector2 pos1, Vector2 pos2)
{
double feta = Math.Atan((pos2.X - pos1.X) / (pos2.Y - pos1.Y));
if (pos2.Y < pos1.Y)
{
feta += MathHelper.ToRadians(180);
}
return feta;
}
