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