How to Rotate the Player In Direction of Movement?

Hello all,

We’ve finally gotten the player to move left and right, and animation work perfectly. Our latest development is rotating the character in the direction of movement. When I move “right” the player is facing forward, but when I move left the character still faces to the right.

How may we resolve this issue?

Thanks in advance, and have a great day!

-Joshua4missions

using UnityEngine;
using System.Collections;

public class movementAlt : MonoBehaviour {
	
	//Set Player Movement Speed	
	public float speed = 3.4f;
	public float rotSpeed = 1.0f;
	
	// Use this for initialization
	void Start () {
	//Set Starting Location
	transform.position = new Vector3(5, 0, 0);
	}
	
	// Update is called once per frame
	void Update () {
	
		//Directional Movement
		//Move Right
		if(Input.GetKey(KeyCode.D)){
			Debug.Log("Player Pressed the 'D' key");
			transform.Translate(Vector3.forward * speed * Time.deltaTime);
			transform.rotation(0, 270, 0);
			animation.Play("Walk");
			Debug.Log("Walk animation initiated");
		}else {
			Debug.Log("Player is not moving. Initiating 'Idle' state");
			animation.Play("Idle");
		}
		//Move Left
		if(Input.GetKey(KeyCode.A)){
			Debug.Log("Player Pressed the 'A' key");
			transform.Translate(Vector3.back * speed * Time.deltaTime);
			transform.rotation(0, 90, 0);
			animation.Play("Walk");
			Debug.Log("Walk animation initiated");
		}else {
			Debug.Log("Player is not moving. Initiating 'Idle' state");
			animation.Play("Idle");
		}
		//Attack
		if(Input.GetMouseButtonDown(0)){
			//Initiate Attack animation
			animation.Play("Attack");
		}else {
			Debug.Log("Player is not attacking. Initiating 'Idle' state");
			animation.Play("Idle");
		}
		
	}
}

huh! I just dealt with this in a spherical environment last night. Quaternion.LookRotation() to the rescue!

using UnityEngine;
using System.Collections;

public class MoveLook : MonoBehaviour {

	public float lookSpeed = 10;
	private Vector3 curLoc;
	private Vector3 prevLoc;
	
	void Update () 
	{
		InputListen();
		transform.rotation = Quaternion.Lerp (transform.rotation,  Quaternion.LookRotation(transform.position - prevLoc), Time.fixedDeltaTime * lookSpeed);
	}
	
	private void InputListen()
	{
		prevLoc = curLoc;
		curLoc = transform.position;
		
		if(Input.GetKey(KeyCode.A))
			curLoc.x -= 1 * Time.fixedDeltaTime;
		if(Input.GetKey(KeyCode.D))
			curLoc.x += 1 * Time.fixedDeltaTime;
		if(Input.GetKey(KeyCode.W))
			curLoc.z += 1 * Time.fixedDeltaTime;
		if(Input.GetKey(KeyCode.S))
			curLoc.z -= 1 * Time.fixedDeltaTime;
		
		transform.position = curLoc;
		
	}
}

I was working on the same problem.

I had the issue where my object would revert to it’s original position once I let go of the keys. I was able to fix this by containing everything inside of the key presses. This created the issue of the object rotating more than desired if I was going along a diagonal by holding down two buttons. I messed with the order of operations and now have an object rotating in the direction i’m heading no matter what combination of two buttons being pressed.

Not sure if there is a better way to write the code with fewer lines, but it works :slight_smile:

Here’s the final working code:

using UnityEngine;
using System.Collections;

public class Example : MonoBehaviour {
	
	// How fast your object moves
	public float moveSpeed;
	// How fast your object will rotate in the direction of movement
	public float rotationSpeed;
	private Vector3 previousLocation;
	private Vector3 currentLocation;
	
	// Use this for initialization
	void Start () {
		
		moveSpeed = 100;
		rotationSpeed = 5;
		
	}
	
	// Update is called once per frame
	void Update () {
		
		previousLocation = currentLocation;	
		currentLocation = transform.position;
		
		if(Input.GetKey("w")&&Input.GetKey("a"))
		{
			currentLocation.z += moveSpeed * Time.fixedDeltaTime;
			currentLocation.x -= moveSpeed * Time.fixedDeltaTime;
			transform.position = currentLocation;
			transform.rotation = Quaternion.Lerp (transform.rotation, Quaternion.LookRotation(transform.position - previousLocation), Time.fixedDeltaTime * rotationSpeed);
		}
		else if(Input.GetKey("w")&&Input.GetKey("d"))
		{
			currentLocation.z += moveSpeed * Time.fixedDeltaTime;
			currentLocation.x += moveSpeed * Time.fixedDeltaTime;
			transform.position = currentLocation;
			transform.rotation = Quaternion.Lerp (transform.rotation, Quaternion.LookRotation(transform.position - previousLocation), Time.fixedDeltaTime * rotationSpeed);
		}
		else if(Input.GetKey("a")&&Input.GetKey("s"))
		{
			currentLocation.x -= moveSpeed * Time.fixedDeltaTime;
			currentLocation.z -= moveSpeed * Time.fixedDeltaTime;
			transform.position = currentLocation;
			transform.rotation = Quaternion.Lerp (transform.rotation, Quaternion.LookRotation(transform.position - previousLocation), Time.fixedDeltaTime * rotationSpeed);
		}
		else if(Input.GetKey("s")&&Input.GetKey("d"))
		{
			currentLocation.z -= moveSpeed * Time.fixedDeltaTime;
			currentLocation.x += moveSpeed * Time.fixedDeltaTime;
			transform.position = currentLocation;
			transform.rotation = Quaternion.Lerp (transform.rotation, Quaternion.LookRotation(transform.position - previousLocation), Time.fixedDeltaTime * rotationSpeed);
		} 
		else if(Input.GetKey("w"))
		{
			currentLocation.z += moveSpeed * Time.fixedDeltaTime;
			transform.position = currentLocation;
			transform.rotation = Quaternion.Lerp (transform.rotation, Quaternion.LookRotation(transform.position - previousLocation), Time.fixedDeltaTime * rotationSpeed);
		} 
		else if(Input.GetKey("a"))
		{
			currentLocation.x -= moveSpeed * Time.fixedDeltaTime;
			transform.position = currentLocation;
			transform.rotation = Quaternion.Lerp (transform.rotation, Quaternion.LookRotation(transform.position - previousLocation), Time.fixedDeltaTime * rotationSpeed);
		} 
		else if(Input.GetKey("s"))
		{
			currentLocation.z -= moveSpeed * Time.fixedDeltaTime;
			transform.position = currentLocation;
			transform.rotation = Quaternion.Lerp (transform.rotation, Quaternion.LookRotation(transform.position - previousLocation), Time.fixedDeltaTime * rotationSpeed);
		} 
		else if(Input.GetKey("d"))
		{
			currentLocation.x += moveSpeed * Time.fixedDeltaTime;
			transform.position = currentLocation;
			transform.rotation = Quaternion.Lerp (transform.rotation, Quaternion.LookRotation(transform.position - previousLocation), Time.fixedDeltaTime * rotationSpeed);
		} 
		
	}
	
}

This is the better way and shorter I kown so I share it to people with problems to solve this. I’m using Rigidbody velocity to move and previous and current position just to calculate look direction of the character… movSpeed around 300f, lookSpeed around 8f. Note: I use FixedUpdate instead of Update

        private void Move()
        {
            prevPos = curPos;
            curPos = transform.position;
    
            float hor = Input.GetAxisRaw("Horizontal") * Time.fixedDeltaTime;
            float ver = Input.GetAxisRaw("Vertical") * Time.fixedDeltaTime;
            curPos.x += hor;
            curPos.z += ver;
    
            Vector3 vel = new Vector3(hor, 0f, ver) * movSpeed;
            rb.velocity = vel;
    
            if (rb.velocity != Vector3.zero) {
                animator.SetBool("Running", true);
                transform.rotation = Quaternion.Normalize(Quaternion.Lerp(transform.rotation, Quaternion.LookRotation(curPos - prevPos), Time.fixedDeltaTime * lookSpeed));
            }
            else { animator.SetBool("Running", false); }
        }

Add the script below to your gameobject

    void Update()
    {
          if (Input.GetKeyDown(KeyCode.A))
          {
               //your other codes
               transform.Rotate(0, -45, 0);
          }
          else if (Input.GetKeyDown(KeyCode.D))
          {
               //your other codes
               transform.Rotate(0, 45, 0);
          }
    }

Thanks Kanox!