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

Unity中使用AddForce时,如何仅限制XZ轴Velocity而保留Y轴?

Unity角色移动速度限制导致跳跃异常的解决方法

我在Unity中使用AddForce实现角色水平移动,为防止玩家速度无限提升,用Vector3.ClampMagnitude限制velocity。这能正常限制水平速度,但会同时限制Y轴速度,导致角色无法正常跳跃(比如跳跃高度不足、下落速度过慢)。

当前代码

if (moveDir.magnitude >= 0.1f)
{
    controller.AddForce(moveDir * moveSpeed, ForceMode.Impulse);
    // 需要修复:这会同时限制Y轴速度,导致下落变慢
    controller.velocity = Vector3.ClampMagnitude(controller.velocity, moveSpeed);
    // 播放移动动画
    animationCaller.Animation_Move(animator);
}
else
{
    // 需要修复:这会同时限制Y轴速度,导致下落变慢
    controller.velocity = Vector3.ClampMagnitude(controller.velocity, 0f);
    controller.angularVelocity = Vector3.ClampMagnitude(controller.angularVelocity, 0f);
    // 播放 idle 动画
    animationCaller.Animation_Idle(animator);
}

尝试过的方法(无效)

我试过分离Y轴速度,限制后重新添加,但会导致水平速度无法回落:

controller.AddForce(moveDir * moveSpeed, ForceMode.Impulse);

/*
Vector3 clampVelocity;
clampVelocity.x = 0;
clampVelocity.y = controller.velocity.y;
clampVelocity.z = 0;
*/

controller.velocity = Vector3.ClampMagnitude(controller.velocity, moveSpeed); // + clampVelocity;

正确解决方案

核心思路是只限制水平方向的速度分量,完全保留Y轴速度(跳跃、重力下落的速度不受影响):

if (moveDir.magnitude >= 0.1f)
{
    controller.AddForce(moveDir * moveSpeed, ForceMode.Impulse);

    // 提取水平速度,单独限制大小,保留Y轴原始速度
    Vector3 horizontalVelocity = new Vector3(controller.velocity.x, 0, controller.velocity.z);
    horizontalVelocity = Vector3.ClampMagnitude(horizontalVelocity, moveSpeed);
    controller.velocity = new Vector3(horizontalVelocity.x, controller.velocity.y, horizontalVelocity.z);

    animationCaller.Animation_Move(animator);
}
else
{
    // 只重置水平速度,保留Y轴速度(比如下落、跳跃过程中的速度)
    Vector3 horizontalVelocity = Vector3.ClampMagnitude(new Vector3(controller.velocity.x, 0, controller.velocity.z), 0f);
    controller.velocity = new Vector3(horizontalVelocity.x, controller.velocity.y, horizontalVelocity.z);
    controller.angularVelocity = Vector3.ClampMagnitude(controller.angularVelocity, 0f);

    animationCaller.Animation_Idle(animator);
}

原理说明

  1. 从当前velocity中提取出水平分量(X和Z轴,Y轴设为0)
  2. 对水平分量使用Vector3.ClampMagnitude限制最大速度
  3. 将限制后的水平分量与原始Y轴速度重新组合,赋值给controller.velocity
  4. idle状态下只重置水平速度,避免影响角色的跳跃或下落过程

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.04 02:15:26