如何使播放器朝其面对的方向移动

时间:2018-12-27 17:08:58

标签: c# unity3d

我的这款游戏仍然在开发中。到目前为止,我的移动代码可以使用箭头键移动播放器。我还具有使用鼠标移动播放器的功能。它将使播放器了解其面对的方式。假设玩家朝左。如果我单击向上箭头键,它仍会向前移动。我想将播放器朝其面对的方向移动。

代码:

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;
  }
 }
}

1 个答案:

答案 0 :(得分:1)

使用transform.forward获取玩家面对的方向。

它始终是一个单位矢量,因此,如果您只想在玩家的前进方向上将位置移动一个单位,则只需将其添加到transform.position

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