Unity 3D中WASD移动控制反向问题求助
Unity FPS角色移动反向控制问题修复方案
问题根源与修正点
- 移动方向未转换到世界空间:你已经通过
transform.TransformDirection()将本地方向转为世界空间的velocity,但最后传给controller.Move()的却是原始的本地direction,这导致移动方向不跟随角色视角,反向移动必然出错。 - 变量未声明:代码中
controller变量没有定义,需要补充声明。 - 干扰移动逻辑的代码:
transform.position = navMeshAgent.nextPosition;会强制覆盖CharacterController计算出的位置,除非你需要结合NavMesh导航功能,否则应该移除这行。 - 重力计算帧率无关性:重力计算需要乘以
Time.deltaTime,避免不同帧率下重力效果不一致。
修正后的完整代码
using UnityEngine; using UnityEngine.AI; public class PlayerMovement : MonoBehaviour { [SerializeField] private float speed = 5f; [SerializeField] private float gravity = 9.81f; [SerializeField] private NavMeshAgent navMeshAgent; // 若不需要NavMesh可删除 private CharacterController controller; void Start() { controller = GetComponent<CharacterController>(); } void Update() { // 获取WASD输入的本地方向 Vector3 direction = new Vector3(Input.GetAxis("Horizontal1"), 0, Input.GetAxis("Vertical1")); // 归一化避免斜向移动速度过快 if (direction.magnitude > 1f) direction.Normalize(); // 转换为世界空间方向并计算速度 Vector3 velocity = transform.TransformDirection(direction) * speed; // 应用重力(CharacterController需要手动处理Y轴) velocity.y -= gravity * Time.deltaTime; // 执行移动 controller.Move(velocity * Time.deltaTime); // 若不需要NavMesh导航,直接删除下面这行 // transform.position = navMeshAgent.nextPosition; } }
额外说明
- 加入方向归一化是为了防止斜向(同时按W+A这类组合键)时移动速度过快,保证所有方向移动速度一致。
- 如果你确实需要结合NavMeshAgent使用,建议不要同时用CharacterController和NavMeshAgent控制移动,二者选一,或者通过NavMeshAgent设置速度而非直接覆盖位置。
内容的提问来源于stack exchange,提问作者Tasos_Noutsis
相关产品推荐
相关产品推荐

