You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Unity 3D中WASD移动控制反向问题求助

Unity FPS角色移动反向控制问题修复方案

问题根源与修正点

  1. 移动方向未转换到世界空间:你已经通过transform.TransformDirection()将本地方向转为世界空间的velocity,但最后传给controller.Move()的却是原始的本地direction,这导致移动方向不跟随角色视角,反向移动必然出错。
  2. 变量未声明:代码中controller变量没有定义,需要补充声明。
  3. 干扰移动逻辑的代码:transform.position = navMeshAgent.nextPosition;会强制覆盖CharacterController计算出的位置,除非你需要结合NavMesh导航功能,否则应该移除这行。
  4. 重力计算帧率无关性:重力计算需要乘以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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.02 23:30:55