Unity 3D角色本地移动问题:旋转后无法朝向自身方向移动
解决Unity角色旋转后无法按本地方向移动的问题
你的核心问题在于:Input.GetAxis("Horizontal") 和 Input.GetAxis("Vertical") 返回的是世界空间下的方向向量,当角色旋转后,这些向量并没有跟随角色的朝向变化,导致移动方向与角色朝向脱节。
只需要修改MovePlayer方法,将输入方向转换为角色的本地空间方向即可,同时要注意保留刚体的Y轴速度(避免覆盖重力或跳跃的速度):
using System.Collections; using System.Collections.Generic; using UnityEngine; public class Movement : MonoBehaviour { public float MovementSpeed = 1000; public float JumpHeight = 2; public Rigidbody rb; public Vector3 PlayerMovement; public float CameraSpeed = 5; public Vector3 CamMovement; void Start() { // 确保获取到Rigidbody组件 if (rb == null) rb = GetComponent<Rigidbody>(); } void Update() { PlayerMovement = new Vector3(Input.GetAxis("Horizontal"), 0, Input.GetAxis("Vertical")); CamMovement = new Vector3(Input.GetAxis("Mouse X") * CameraSpeed, 0, 0); transform.Rotate(0, CamMovement.x, 0, Space.Self); } private void FixedUpdate() { MovePlayer(PlayerMovement); } void MovePlayer(Vector3 direction) { // 1. 归一化输入方向,防止斜向移动速度过快 if (direction.magnitude > 1) direction = direction.normalized; // 2. 将世界空间方向转换为角色本地空间方向 Vector3 localDirection = transform.TransformDirection(direction); // 3. 保留刚体当前的Y轴速度(避免覆盖重力/跳跃),设置XZ轴的移动速度 rb.velocity = new Vector3(localDirection.x * MovementSpeed * Time.deltaTime, rb.velocity.y, localDirection.z * MovementSpeed * Time.deltaTime); } }
关键修改点说明:
- 方向转换:使用
transform.TransformDirection(direction)将输入的世界空间方向转为角色自身的本地空间方向,这样角色旋转后,移动方向会自动跟随朝向。 - 速度归一化:当同时按下水平和垂直方向键时,输入向量的长度会大于1,导致移动速度翻倍,归一化后可以保证所有方向的移动速度一致。
- 保留Y轴速度:直接设置
rb.velocity会覆盖Y轴的速度,导致重力和跳跃失效,所以只修改X和Z轴的速度,保留原有的Y轴速度。
另外,建议在Start方法中添加对Rigidbody的空值检查,避免空引用错误。
内容的提问来源于stack exchange,提问作者DINOTICK
相关产品推荐
相关产品推荐

