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

Unity中如何让Rigidbody实现平滑跳跃?

解决Rigidbody角色跳跃卡顿的问题

核心问题分析

你的跳跃卡顿主要源于两个关键错误:

  • 水平移动强制重置Y轴速度:CalculateMovement()方法中直接将rb.velocity.y设为0,这会在FixedUpdate每帧覆盖跳跃的Y轴速度,导致跳跃动作被强制打断,出现卡顿。
  • 跳跃逻辑存在冗余与错误:使用ForceMode.Force施加跳跃力不合适(该模式是持续力,不适合瞬间跳跃),且速度计算数值过大,同时没有判断角色是否在地面,可能触发多次跳跃导致物理状态混乱。

修改后的完整脚本

using UnityEngine;
using UnityEngine.InputSystem;

public class Controller : MonoBehaviour
{
    [Tooltip("挂载在玩家身上的Rigidbody组件")]
    public Rigidbody rb;
    private bool isGrounded = false;

    private float movementX;
    private float gravity = -9.81f;
    public float moveSpeed = 10f;
    public float jumpForce = 5f; // 直接设置跳跃初速度,更直观可控
    public float fallMultiplier = 2.5f; // 下落加速优化,提升跳跃手感

    void Start()
    {
        rb = GetComponent<Rigidbody>();
        rb.freezeRotation = true; // 锁定旋转,避免角色移动时倾倒
    }

    // 稳定检测是否在地面
    void OnCollisionStay(Collision collision)
    {
        if (collision.gameObject.CompareTag("Ground"))
        {
            isGrounded = true;
        }
    }

    void OnCollisionExit(Collision collision)
    {
        if (collision.gameObject.CompareTag("Ground"))
        {
            isGrounded = false;
        }
    }

    void OnMove(InputValue movementValue)
    {
        Vector2 movementVector = movementValue.Get<Vector2>();
        movementX = movementVector.x;
    }

    void OnJump()
    {
        // 仅在地面时触发跳跃
        if (isGrounded)
        {
            // 直接设置Y轴速度,保证跳跃瞬间的平滑性
            rb.velocity = new Vector3(rb.velocity.x, jumpForce, rb.velocity.z);
            isGrounded = false;
        }
    }

    void CalculateMovement()
    {
        // 保留原有Y轴速度,仅修改X轴移动速度
        Vector3 movementVelocity = new Vector3(movementX * moveSpeed, rb.velocity.y, 0);
        rb.velocity = movementVelocity;

        // 下落加速优化,让跳跃的下落阶段更自然
        if (rb.velocity.y < 0)
        {
            rb.velocity += Vector3.up * gravity * (fallMultiplier - 1) * Time.fixedDeltaTime;
        }
    }

    void FixedUpdate()
    {
        CalculateMovement();
    }
}

额外优化建议

  • Rigidbody组件设置:将Collision Detection设为Continuous Dynamic,避免高速移动时穿模,同时提升跳跃碰撞检测的精准度;调整Mass到1-2的合理区间,质量过大会增加物理计算负担,导致卡顿。
  • 输入系统设置:确保新输入系统中Jump动作的Action Type设为Button,避免重复触发跳跃指令。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.13 05:50:40