繁体   English   中英

如何让玩家朝着它所面对的方向移动

[英]How to make the player move in the direction it is facing

我有这个仍在开发中的统一游戏。 到目前为止,我的移动代码可以用箭头键移动玩家。 我还有一个功能可以用鼠标移动播放器。 它让玩家改变它面对的方式。 假设玩家面向左侧。 如果我点击向上箭头键,它仍然向前移动。 我想将玩家朝它所面对的方向移动。

代码:

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

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

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM