简体   繁体   English

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

[英]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;
  }
 }
}

Use transform.forward to get the direction the player is facing.使用transform.forward获取玩家面对的方向。

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 :它始终是一个单位向量,因此如果您只想在玩家向前的方向上将位置移动一个单位,您只需将其添加到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