# How to set player rotation to direction the player is moving?

I'm having an issue with my click to move mechanic. I want the player to move to a specific position in the game when the mouse is clicked (and it does just that) but the issue I'm having is that the player doesn't face the direction in which it is travelling.

Lets say I click a position diagonally right to where the player is. Immediately after clicking that point, the character will face that direction and run to it, instead of facing the direction it has to take to get there... if that makes sense.

Here's my code snippet:

public void moveToTargetPosition() {
Seeker seeker = GetComponent<Seeker>();
seeker.StartPath (transform.position, targetPlayerPosition, OnPathComplete);

transform.rotation = Quaternion.Lerp (transform.rotation,  Quaternion.LookRotation(targetPlayerPosition - transform.position), Time.fixedDeltaTime * lookSpeed);
}


Obviously I'm missing some modifier in here.

Any ideas?

Thanks!

In 2D you can use Atan2 (http://docs.unity3d.com/ScriptReference/Mathf.Atan2.html)

facing_angle = Mathf.Atan2( new_pos.y - old_pos.y, new_pos.x - old_pos.x);


Or using (X,Z) if that's how your world is oriented:

facing_angle = Mathf.Atan2( new_pos.z - old_pos.z, new_pos.x - old_pos.x);


Or Transform.LookAt (http://docs.unity3d.com/ScriptReference/Transform.LookAt.html)

public function LookAt(worldPosition: Vector3, worldUp: Vector3 = Vector3.up): void;


This will point your character toward worldPosition.

Your character might needs additional rotation if its 3D mesh was exported facing the "wrong" way, you can do this by adding to localEulerAngles in the transform or using quaternions but it's better to fix the source mesh if you can.

Your code would face towards the destination, and it seems like you're following some kind of path. The problem is that if the direction you're traveling isn't the same as the look at to the goal, it'll look odd.

You can solve this by either getting the direction you're traveling in and using that instead. (This is specific to how you're moving it, however if you use Physics(2D) you can use the velocity.)

Or if there's no way to get that, you can use a slight trick where you set the direction based on the delta position you've had since last step.

private Vector3 _previousPosition;
public void moveToTargetPosition() {
Seeker seeker = GetComponent<Seeker>();
seeker.StartPath (transform.position, targetPlayerPosition, OnPathComplete);

Vector3 currPosition = transform.position;
transform.rotation = Quaternion.Lerp (transform.rotation,  Quaternion.LookRotation(currPosition - _previousPosition), Time.fixedDeltaTime * lookSpeed);
_previousPosition = currPosition;
}