# Angle between two points

I have a character who walks to random points in my room in Unity. The problem is he always faces one direction, I want to write in C# a piece of code that will get the direction the character is currently facing and the position of the target, then works out the angle between them to turn the character that amount. I have tried the LookAt function but that makes the character walk in an arc shape towards the target which looks very unnatural as it constantly looks at the target.

• I can't write a proper answer now, but you need basic trig. Google polar coordinates and atan2. – jcora Jul 20 '12 at 14:26

The LookAt function does this for you. You may be using it improperly, or something is wrong with your steering if you're having problems with this. You can try it this way too:

//find the vector pointing from our position to the target
dir = (Target.position - transform.position).normalized;

//create the rotation to look at the target
rotation = Quaternion.LookRotation(dir);


Now you can either snap towards that rotation, or you can do it slowly over time. (slowly over time means all this code needs to go into the update function)

//rotate over time
transform.rotation = Quaternion.Slerp(transform.rotation, rotation, Time.deltaTime * RotationSpeed);

//snap rotation
transform.rotation = rotation;


For 2D another alternate method would be Atan2:

angleBetween = Mathf.Atan2(point2Y - point1Y, point2X - point1X) * 180 / Math.PI))

• void FixedUpdate() { // get the current steering direction to reach the target position Vector3 walk = (this.mTargetPosition - this.transform.position).normalized; // ignore 3d walk.y = 0.0f; walk.Normalize(); // move into the desired direction this.transform.LookAt(mTargetPosition); this.transform.Translate(-walk); } } this is the way I have set up the lookat function as is, I can't tell what's wrong with it except I'm assuming maybe it shouldn't be in fixedUpdate? – Darren Jul 20 '12 at 15:09
• I'm not sure. What is it doing? When I work on steering I have debug lines drawn all over the place. I have lines showing the direction goblins are facing, acceleration lines and velocity lines. Set them all to different colors so you know which is which, this will really help with the visual debugging. It lets you know which one doesn't look right and you can then look more into it. – MichaelHouse Jul 20 '12 at 15:18