You need to enable JavaScript to run this app. Unity3D FPS游戏使用CharacterController移动松开按键后滑动问题
优惠活动
大模型
产品
解决方案
定价
更多

Unity3D FPS游戏使用CharacterController移动松开按键后滑动问题

问题根因

松开按键后角色滑动的问题由两个逻辑错误共同导致:

  • 使用了默认带输入平滑的Input.GetAxis接口:Unity 原生Input.GetAxis返回值会做渐变插值,按下按键时从0升到1、松开时从1降到0,不会立刻跳变,这是滑动的核心诱因
  • 输入向量强制归一化逻辑不合理:你对所有输入得到的水平向量直接做normalized处理,哪怕输入轴数值已经降到0.1,归一化后向量模长仍为1,相当于保持满速移动,放大了输入平滑的负面效果

另外你原有代码中的重力计算没有乘Time.deltaTime,会导致下落速度和帧率挂钩,不同设备运行表现不一致,后续修复方案也会同步修正该问题。

直接修复方案

把代码中两处Input.GetAxis替换为Input.GetAxisRaw,同时调整归一化逻辑,仅当输入向量模长大于1时才做归一化,避免慢走时速度被强制拉高:

public float moveSpeed = 5f;
public float jumpForce = 5f;
public CharacterController controller;

private Vector3 moveDirection;
public float gravityScale;

void Start()
{
    controller = GetComponent<CharacterController>();
}

void Update()
{
    float yStore = moveDirection.y;

    // 改用GetAxisRaw,输入无平滑,松开按键立刻返回0
    moveDirection = (transform.forward * Input.GetAxisRaw("Vertical")) + (transform.right * Input.GetAxisRaw("Horizontal"));
    // 仅当输入向量模长大于1时归一化,保证斜向移动速度和单方向移动速度一致
    if (moveDirection.magnitude > 1f)
    {
        moveDirection = moveDirection.normalized;
    }
    moveDirection *= moveSpeed;
    moveDirection.y = yStore;

    if (controller.isGrounded)
    {
        moveDirection.y = 0f;

        if (Input.GetButtonDown("Jump"))
        {
            moveDirection.y = jumpForce;
        }
    }

    // 重力计算补充Time.deltaTime,保证不同帧率下表现一致
    moveDirection.y += Physics.gravity.y * gravityScale * Time.deltaTime;
    controller.Move(moveDirection * Time.deltaTime);
}
可选优化:可控平滑移动

如果觉得Input.GetAxisRaw的移动手感太生硬,想要保留平滑过渡效果又不想出现不受控的滑动,可以自己实现可控的速度过渡逻辑,示例如下:

public float moveSpeed = 5f;
public float jumpForce = 5f;
public CharacterController controller;
// 新增参数,控制移动平滑度,数值越大平滑度越低、响应越快
public float moveSharpness = 15f;
public float gravityScale;

private Vector3 moveDirection;

void Start()
{
    controller = GetComponent<CharacterController>();
}

void Update()
{
    float yStore = moveDirection.y;
    // 计算目标移动速度
    Vector3 targetMove = (transform.forward * Input.GetAxisRaw("Vertical")) + (transform.right * Input.GetAxisRaw("Horizontal"));
    if (targetMove.magnitude > 1f)
    {
        targetMove = targetMove.normalized;
    }
    targetMove *= moveSpeed;
    // 用Lerp做平滑过渡
    moveDirection = Vector3.Lerp(moveDirection, targetMove, moveSharpness * Time.deltaTime);
    moveDirection.y = yStore;

    if (controller.isGrounded)
    {
        moveDirection.y = 0f;

        if (Input.GetButtonDown("Jump"))
        {
            moveDirection.y = jumpForce;
        }
    }

    moveDirection.y += Physics.gravity.y * gravityScale * Time.deltaTime;
    controller.Move(moveDirection * Time.deltaTime);
}

调整moveSharpness参数就可以控制平滑程度,既不会太生硬,也不会出现松开按键后滑出很远的问题。

内容的提问来源于stack exchange,提问作者Tealcy5

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.18 19:45:06