Raghav Herugu
Raghav Herugu

Reputation: 546

How to make the player move in the direction it is facing

I have this game in unity that is still in development. My movement code so far can move the player with arrow keys. I also have a feature to move the player with your mouse. It turns the player on how it is facing. Let's say the player is facing left. If I click on the up arrow key, it still moves forward. I want to move the player in the direction it is facing.

Code:

using System.Collections.Generic;
using UnityEngine;

 public class PlayerMovement : MonoBehaviour {

 public float distance = 5f;

 public Transform playerCam;

 void FixedUpdate () {
  transform.localEulerAngles = new Vector3(transform.localEulerAngles.x, 
  Camera.main.transform.localEulerAngles.y, transform.localEulerAngles.z);
  if (Input.GetKey(KeyCode.LeftArrow))
  {
      Vector3 position = this.transform.position;
      position.x--;
      this.transform.position = position;
  }
  if (Input.GetKey(KeyCode.RightArrow))
  {
      Vector3 position = this.transform.position;
      position.x++;
      this.transform.position = position;
  }
  if (Input.GetKey(KeyCode.UpArrow))
  {
      Vector3 position = this.transform.position;
      position.z++;
      this.transform.position = position;
  }
  if (Input.GetKey(KeyCode.DownArrow))
  {
      Vector3 position = this.transform.position;
      position.z--;
      this.transform.position = position;
  }
  if (Input.GetKey("W"))
  {
      Vector3 position = this.transform.position;
      position.z++;

      this.transform.position = position;
  }
  if (Input.GetKey("S"))
  {
      Vector3 position = this.transform.position;
      position.z--;

      this.transform.position = position;
  }
  if (Input.GetKey("A"))
  {
      Vector3 position = this.transform.position;
      position.x--;

      this.transform.position = position;
  }
  if (Input.GetKey("D"))
  {
      Vector3 position = this.transform.position;
      position.x++;

      this.transform.position = position;
  }
 }
}

Upvotes: 3

Views: 1156

Answers (1)

Ruzihm
Ruzihm

Reputation: 20269

Use transform.forward to get the direction the player is facing.

It will always be a unit vector, so if you just want to move the position by exactly one unit in the player's forward direction, you can just add it to transform.position:

if (Input.GetKey("W")) 
{
    this.transform.position += this.transform.forward;
}

Upvotes: 3

Related Questions