Unity 将玩家移动到他面对的方向(而不是全局空间)



所以我有了这个玩家移动+旋转的脚本。问题是,当我用我的角色转身,然后按键前进时,由于全局空间的原因,情况会很糟糕。。。例如,当我向左转弯时,按下前进键,它会向后转弯并前进,而不是朝着角色所面对的方向前进。我对c#和团结很陌生。所以我很乐意得到任何帮助。非常感谢。

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class SharkMovement : MonoBehaviour
{
private Rigidbody rb;
float xInput;
float zInput;
public float moveSpeed;
public float rotateSpeed;
private Vector3 direction;
private Vector3 fwd;
// Start is called before the first frame update
void Start()
{
rb = GetComponent<Rigidbody>();
}
// Update is called once per frame
void FixedUpdate()
{
// Pohyb ryby
xInput = Input.GetAxisRaw("Horizontal2");
zInput = Input.GetAxisRaw("Vertical2");

direction = new Vector3(xInput, 0.0f, zInput);
if (direction != Vector3.zero)
{
transform.rotation = Quaternion.Slerp(transform.rotation, Quaternion.LookRotation(direction), rotateSpeed * Time.deltaTime);
}

rb.MovePosition(transform.position + moveSpeed * Time.deltaTime * direction);
}
}

您可以使用Transform.forward来获取对象的正向向量。假设zInput是您的前向/后向输入,这样的操作就可以了。

xInput = Input.GetAxisRaw("Horizontal2");
zInput = Input.GetAxisRaw("Vertical2");

direction = new Vector3(xInput, 0.0f, 0.0f) + (zInput * transform.forward);

xInput乘以transform.right,将zInput乘以transform.forward,然后将它们相加:

xInput = Input.GetAxisRaw("Horizontal2");
zInput = Input.GetAxisRaw("Vertical2");

direction = xInput * transform.right + zInput * transform.forward;

你可能还应该把幅度限制为1,这样对角线移动就不会比正交移动快:

xInput = Input.GetAxisRaw("Horizontal2");
zInput = Input.GetAxisRaw("Vertical2");

direction = xInput * transform.right + zInput * transform.forward;
direction = direction.normalized * Mathf.Min(1f, direction.magnitude);

最新更新