Public Group

# Working out the direction an object should be facing

This topic is 4852 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

## Recommended Posts

Hey guys, I'm having a bit of trouble working out how to make my character face the way it is moving on the X and Z axis. Currently I have this:
public void UpdateTrajectory(Vector3 newLocation)
{
//here we need to work out the angle in radians
//with oldLoc as the origin, and new Loc as the point
//let trajectory = angle in radians
float X1 = oldLocation.X;
float X2 = newLocation.X;
float Z1 = oldLocation.Z;
float Z2 = newLocation.Z;
float A = Z2 - Z1;
float B = X2 - X1;
if(A==0 || B==0)
{
if(A == 0 && B &lt; 0)
{
trajectory = 3 * (float)Math.PI/2;
//left
}
if(A == 0 && B &gt; 0)
{
trajectory = 5 * (float)Math.PI/2;
//right
}
if(B == 0 && A &lt; 0)
{
trajectory = 2 * (float)Math.PI/2;
//forward
}
if(B == 0 && A &gt; 0)
{
trajectory = 4 * (float)Math.PI/2;
//backward
}
}
else
{
float Tangent = A/B;
float newTraj = (float)Math.Atan((double)Tangent);
trajectory = newTraj;
System.Diagnostics.Debug.Write("(T = " + trajectory + ")");
trajectory = (float)Math.PI - trajectory;
}
}


I know the code is messy as crap now, and I've been modifying it a lot. oldLocation is a global Vector3 for the current position, newLocation being a Vector3 for the next location. trajectory (which might not be the best name for it) is the amount in radians I am rotating the object, and is also global. The if clause is in there to solve a divide by 0 problem. Currently the character rotates, but back left is the same as forward right and back right is the same as forward left. Can anyone help? if you need any more info, I'll happily post it.

##### Share on other sites
You might look into using atan2() rather than atan(). It would eliminate most of the special-case code, and might solve whatever problems you're having as well.

##### Share on other sites
Wow, thanks Jyk, that worked an absolute treat.

1. 1
2. 2
3. 3
Rutin
17
4. 4
5. 5

• 14
• 9
• 9
• 9
• 10
• ### Forum Statistics

• Total Topics
632912
• Total Posts
3009186
• ### Who's Online (See full list)

There are no registered users currently online

×