Sign in to follow this  

Working out the direction an object should be facing

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

If you intended to correct an error in the post then please contact us.

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 < 0)
		{
			trajectory = 3 * (float)Math.PI/2;
			//left
         	}
		if(A == 0 && B > 0)
		{
			trajectory = 5 * (float)Math.PI/2;
			//right
		}
		if(B == 0 && A < 0)
		{
			trajectory = 2 * (float)Math.PI/2;
			//forward
		}
		if(B == 0 && A > 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 this post


Link to post
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 this post


Link to post
Share on other sites

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

If you intended to correct an error in the post then please contact us.

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this