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

Unity中CharacterController.Move函数为何无法移动玩家对象?

问题根因与修复方案

核心代码Bug

你的代码里计算移动向量时使用的trueSpeed变量从未被赋值,C#中float类型字段默认值为0,无论你在Inspector里把currentSpeed调到多高,和0相乘后得到的移动向量永远是零向量,自然不会产生任何位移。

其他会导致移动失效的常见排查点

  • 检查CharacterController碰撞体初始位置:如果玩家生成时直接卡在地面碰撞体、墙体碰撞体内部,碰撞检测会阻挡所有位移
  • 检查脚本启用状态:确认Inspector面板中脚本组件前方的勾选框为选中状态,禁用的脚本不会执行Update逻辑
  • 检查全局时间缩放:如果项目其他逻辑把Time.timeScale设为0,Time.deltaTime返回值为0,最终计算的移动距离也会是0
  • 缺失重力赋值:CharacterController不会自动应用重力,不给竖直方向添加重力值的话,组件会卡在地面碰撞层,间接导致水平移动异常

修复后的完整代码

using UnityEngine;

public class CharacterMovementController : MonoBehaviour {
    Animator characterAnimator;
    CharacterController character;
    [SerializeField] Transform mainCamera;
    [SerializeField] float sprintBoost = 10f;
    [SerializeField] float currentSpeed = 20f;
    float trueSpeed;

    void Start() {
        characterAnimator = gameObject.GetComponent<Animator>();
        character = gameObject.GetComponent<CharacterController>();
    }

    void Update() {
        // 实时计算实际移动速度,默认走路用currentSpeed,按住左Shift时叠加冲刺速度
        trueSpeed = Input.GetKey(KeyCode.LeftShift) ? currentSpeed + sprintBoost : currentSpeed;

        // 获取轴向输入
        float hInput = Input.GetAxis("Horizontal");
        float vInput = Input.GetAxis("Vertical");

        // 本地坐标系移动(和物体自身朝向对齐)
        Vector3 moveDir = transform.right * hInput + transform.forward * vInput;
        // 如果需要实现相机相对移动(和相机朝向对齐),把上面一行替换为以下逻辑
        // Vector3 camFwd = Vector3.Scale(mainCamera.forward, new Vector3(1,0,1)).normalized;
        // Vector3 camRight = Vector3.Scale(mainCamera.right, new Vector3(1,0,1)).normalized;
        // Vector3 moveDir = camRight * hInput + camFwd * vInput;

        moveDir *= trueSpeed;
        // 追加重力,避免卡地面、斜坡滑动问题
        moveDir.y += Physics.gravity.y * Time.deltaTime;

        // 执行移动
        character.Move(moveDir * Time.deltaTime);
    }
}

原问题组件配置参考

组件配置截图

注意:如果修复后移动方向和输入不匹配,检查玩家模型的初始朝向是否和Transform.forward轴对齐,不对齐的话可以给模型加一层父物体调整朝向即可。

内容的提问来源于stack exchange,提问作者The One Who Will

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.28 00:03:34