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); }
原理说明
- 从当前
velocity中提取出水平分量(X和Z轴,Y轴设为0) - 对水平分量使用
Vector3.ClampMagnitude限制最大速度 - 将限制后的水平分量与原始Y轴速度重新组合,赋值给
controller.velocity - idle状态下只重置水平速度,避免影响角色的跳跃或下落过程
内容的提问来源于stack exchange,提问作者CubeGamer
相关产品推荐
相关产品推荐

