【问题标题】:How to make the player move in the direction it is facing如何让玩家朝着它所面对的方向移动
【发布时间】:2018-12-27 17:08:58
【问题描述】:

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

代码:

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

【问题讨论】:

标签: c# unity3d


【解决方案1】:

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

它总是一个单位向量,所以如果你只想将位置在玩家的前进方向上移动一个单位,你可以将它添加到transform.position

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

【讨论】:

  • 非常感谢。它确实有帮助,但假设我想让玩家朝着它所面对的方向向后移动?我试过 this.transform.position += this.transform.backward
  • 没有transform.backward。您必须改用this.transform.position -= this.transform.forward
猜你喜欢
  • 2014-06-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-10-28
相关资源
最近更新 更多