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

Unity中如何实现角色的动态跳跃效果?

Unity角色动态跳跃的优化实现方案

1. 基于CharacterController的直接位移控制(适合非纯物理驱动的角色)

如果用物理引擎加力没达到预期,大概率是角色受重力、摩擦等物理参数干扰过多。用CharacterController可以直接控制位移,手感更精准可控:

using UnityEngine;

public class PlayerJump : MonoBehaviour
{
    public CharacterController controller;
    public float jumpHeight = 2f;
    public float gravity = -9.81f;
    private Vector3 velocity;
    private bool isGrounded;

    void Update()
    {
        // 利用CharacterController自带的接地检测
        isGrounded = controller.isGrounded;

        // 落地时重置垂直速度,避免重力累积导致落地卡顿
        if (isGrounded && velocity.y < 0)
        {
            velocity.y = -2f;
        }

        // 响应跳跃输入(示例为空格)
        if (Input.GetButtonDown("Jump") && isGrounded)
        {
            // 用物理公式计算跳跃初速度,保证高度稳定
            velocity.y = Mathf.Sqrt(jumpHeight * -2f * gravity);
        }

        // 应用重力
        velocity.y += gravity * Time.deltaTime;
        // 执行角色移动
        controller.Move(velocity * Time.deltaTime);
    }
}

这种方式完全由代码控制跳跃节奏,不受物理材质、刚体质量等参数影响,特别适合平台跳跃类游戏。

2. 优化Rigidbody的加力方式(适合物理驱动的角色)

如果必须依赖物理引擎,试试调整加力逻辑,解决之前的手感问题:

  • 仅在角色接地时施加跳跃力,避免空中误触发
  • 用Impulse模式瞬间施加冲量,比Force模式更贴合跳跃的瞬时发力特性
  • 锁定刚体旋转,防止跳跃时角色翻倒破坏手感
using UnityEngine;

public class RigidbodyJump : MonoBehaviour
{
    public Rigidbody rb;
    public float jumpForce = 5f;
    public float groundCheckDistance = 0.1f;
    public LayerMask groundLayer;
    private bool isGrounded;

    void FixedUpdate()
    {
        // 用射线检测接地,比依赖Rigidbody.isGrounded更可靠
        isGrounded = Physics.Raycast(transform.position, Vector3.down, groundCheckDistance, groundLayer);
    }

    void Update()
    {
        if (Input.GetButtonDown("Jump") && isGrounded)
        {
            // 先重置垂直速度,消除重力对跳跃高度的干扰
            rb.velocity = new Vector3(rb.velocity.x, 0f, rb.velocity.z);
            // 向上施加冲量
            rb.AddForce(Vector3.up * jumpForce, ForceMode.Impulse);
        }
    }

    void OnDrawGizmos()
    {
        // 绘制检测射线,方便调试接地范围
        Gizmos.color = Color.red;
        Gizmos.DrawRay(transform.position, Vector3.down * groundCheckDistance);
    }
}

注意:给刚体设置1-2的Mass值,Drag和AngularDrag不要过高,否则会削弱跳跃的爽快感。

3. 动画曲线配合优化动态手感

不管用哪种跳跃实现方式,配合动画曲线能让动作更自然:

  • 在Animator中给跳跃动画添加JumpCurve参数,用AnimationCurve编辑跳跃过程中角色的Y轴偏移
  • 代码中根据垂直速度的变化驱动曲线值,让角色跳跃时有轻微的身体起伏,提升动态感

常见问题排查

  • 跳跃高度不稳定/手感飘:检查Rigidbody相关操作是否放在FixedUpdate中(物理逻辑必须在FixedUpdate处理,Update仅处理输入)
  • 接地检测不准:不要依赖Rigidbody.isGrounded,改用射线、胶囊体检测,或CharacterController的自带检测
  • 跳跃后速度异常:施加跳跃力前重置垂直速度,避免叠加重力影响

内容的提问来源于stack exchange,提问作者邢方帅

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.24 12:57:46