Unity:如何在不改变跳跃高度的前提下减慢跳跃动作?
我希望让跳跃动作比当前更慢,目前我使用
rb.AddForce(Vector3.up * JumpPower);来使玩家沿Y轴跳跃,玩家能够跳到我想要的高度,但所用时长不符合要求。请问是否有办法在不改变玩家跳跃高度的前提下,延长跳跃时长?
我曾尝试修改JumpPower变量,但正如预期,修改该变量时,跳跃时长改变的同时,玩家的跳跃高度也会随之变化。
以下是我的代码:using System.Collections; using System.Collections.Generic; using UnityEngine; public class movement : MonoBehaviour { public Rigidbody rb; public float MouseSensitivity; public float MoveSpeed; public float JumpPower; private Vector3 targetMoveDirection; // Smoothing factors public float moveSmoothing = 0.1f; public float rotateSmoothing = 0.1f; bool isJumping = false; void Start() { //Cursor.visible = false; } void Update() { // Move targetMoveDirection = transform.forward * Input.GetAxis("Vertical") + transform.right * Input.GetAxis("Horizontal"); rb.AddForce(targetMoveDirection * MoveSpeed, ForceMode.VelocityChange); Vector3 newVelocity = rb.velocity; newVelocity.x = Mathf.Lerp(rb.velocity.x, 0, moveSmoothing); newVelocity.z = Mathf.Lerp(rb.velocity.z, 0, moveSmoothing); rb.velocity = newVelocity; // Jump if (Mathf.Abs(rb.velocity.y) < 0.01f && !isJumping) { if (Input.GetKeyDown(KeyCode.Space)) { rb.AddForce(Vector3.up * JumpPower); } } } }
解决方案
核心逻辑是:跳跃高度由初速度和重力的比值决定(公式为 h = v²/(2g)),只要保证 v²/g 的值不变,高度就不会改变。降低重力加速度并对应降低初速度,就能延长跳跃的总时长。下面是两种可行的实现方式:
方法一:修改Rigidbody重力缩放(简单直接)
- 调整重力强度:给玩家的Rigidbody组件设置小于1的
Gravity Scale(比如0.5),让重力作用变弱,物体上升和下落的速度都会减慢。 - 同步修正跳跃力:按照公式
新JumpPower = 原JumpPower * sqrt(新重力缩放值)计算新的跳跃力。比如原重力缩放为1,新值设为0.5,那么新JumpPower就是原数值乘以√0.5≈0.707,这样能保证跳跃高度完全不变。
也可以在代码中动态处理,避免手动计算:
// 新增公开变量,用于设置目标重力缩放比例 public float targetGravityScale = 0.5f; void Start() { // 应用自定义重力缩放 rb.gravityScale = targetGravityScale; // 自动修正跳跃力,维持原有高度 JumpPower *= Mathf.Sqrt(targetGravityScale); }
方法二:自定义重力控制(灵活度更高)
如果不想修改全局重力规则,可以手动控制y轴的重力,完全替代Unity的默认重力:
- 先把Rigidbody的
Gravity Scale设为0,关闭默认重力。 - 在代码中手动施加向下的重力,并直接基于目标高度计算跳跃初速度:
修改后的核心代码如下:
public float customGravity = 9.81f; // 自定义重力值,默认和Unity一致 public float desiredJumpHeight = 2f; // 直接设定想要的跳跃高度 private float jumpVelocity; void Start() { rb.gravityScale = 0; // 根据目标高度和自定义重力,计算所需的跳跃初速度 jumpVelocity = Mathf.Sqrt(2 * desiredJumpHeight * customGravity); } void FixedUpdate() { // 手动施加自定义重力 rb.AddForce(Vector3.down * customGravity * rb.mass, ForceMode.Force); // 原有移动逻辑保持不变... // 跳跃逻辑 if (Mathf.Abs(rb.velocity.y) < 0.01f) { if (Input.GetKeyDown(KeyCode.Space)) { rb.velocity = new Vector3(rb.velocity.x, jumpVelocity, rb.velocity.z); } } }
需要延长跳跃时长时,直接降低customGravity的值即可——比如改成4.9,跳跃时长会变为原来的√2倍,同时高度始终维持desiredJumpHeight的设定值。
额外优化提示
你的原代码中isJumping变量没有被正确更新,可能导致跳跃逻辑异常,建议补充落地检测的标记重置:
void FixedUpdate() { // 检测是否落地 if (Mathf.Abs(rb.velocity.y) < 0.01f) { isJumping = false; } // 跳跃触发逻辑 if (!isJumping && Input.GetKeyDown(KeyCode.Space)) { rb.AddForce(Vector3.up * JumpPower); isJumping = true; } }
内容的提问来源于stack exchange,提问作者neviot
相关产品推荐
相关产品推荐

