c# - 如何让玩家朝它面对的方向移动

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

最佳答案

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

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

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

关于c# - 如何让玩家朝它面对的方向移动,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53948519/

相关文章:

android - 统一: Edit Gradle file of Android modules in Unity Assets

c# - 为多个应用程序创建 VSTO 插件

c# - 如何使用 Mono.CSharp.Evaluator 编译委托(delegate)?

c# - 映射相同类型的模型以查看实例

c# - 如何将 Sprite 完全移出屏幕?

c# - Resource.Load 不会在 Unity 中加载最新文件

c# - 获取程序集路径 C#

c# - ConfigurationManager.AppSettings[key] 始终为空

c# - 从动态字典中包含的元素获取属性的更快方法?

android - 从 Android 应用程序启动 Unity 游戏并从 Unity 恢复到该应用程序是否可行?