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

Unity 2D平台跳跃优化:如何实现离地缓冲跳跃与二次跳功能?

解决方案:实现缓冲跳跃与二次跳跃

针对你的2D平台跳跃游戏需求,以下是具体的代码修改方案,解决缓冲跳跃(Coyote Time)和二次跳跃的问题:

一、核心变量添加

在类中新增以下可控变量,用于实现两个功能的逻辑控制:

// 缓冲跳跃时长(单位:秒),可在Inspector面板调整
public float coyoteTime = 0.15f;
// 缓冲时间计数器
private float coyoteTimeCounter;

// 最大跳跃次数(设为2即支持二次跳)
public int maxJumps = 2;
// 当前剩余跳跃次数
private int currentJumpCount;

二、修改地面检测逻辑

替换原有的地面触发回调,并在FixedUpdate中维护缓冲计时器:

private void OnTriggerEnter2D(Collider2D other)
{
    if (other.CompareTag("Floor"))
    {
        isGrounded = true;
        // 回到地面时重置跳跃次数和缓冲计时器
        currentJumpCount = maxJumps;
        coyoteTimeCounter = coyoteTime;
        animator.SetBool("IsJumping", false);
    }
}

private void OnTriggerExit2D(Collider2D other)
{
    if (other.CompareTag("Floor"))
    {
        // 离开地面时不立刻标记未接地,而是启动缓冲计时器
        coyoteTimeCounter = coyoteTime;
    }
}

private void FixedUpdate()
{
    rb.velocity = new Vector2(horizontal * speed, rb.velocity.y);

    if (horizontal > 0 && !facingRight)
    {
        Flip();
    }
    if (horizontal < 0 && facingRight)
    {
        Flip();
    }

    animator.SetFloat("Speed", Mathf.Abs(horizontal));
    animator.SetFloat("yVelocity", rb.velocity.y);

    // 仅在未接地时递减缓冲计时器,时间耗尽后才标记未接地
    if (!isGrounded)
    {
        coyoteTimeCounter -= Time.fixedDeltaTime;
        if (coyoteTimeCounter <= 0)
        {
            isGrounded = false;
        }
    }
}

三、修改跳跃触发逻辑

更新Update中的跳跃判断,同时支持缓冲跳跃和二次跳跃:

void Start()
{
    // 初始化跳跃次数
    currentJumpCount = maxJumps;
}

void Update()
{
    horizontal = Input.GetAxisRaw("Horizontal");

    if (Input.GetButtonDown("Jump"))
    {
        // 满足缓冲条件或还有剩余跳跃次数时触发跳跃
        if ((isGrounded || coyoteTimeCounter > 0) && currentJumpCount > 0)
        {
            // 直接设置Y轴速度,精准控制跳跃高度
            rb.velocity = new Vector2(rb.velocity.x, jump);
            currentJumpCount--;
            animator.SetBool("IsJumping", true);

            // 触发缓冲跳跃后立刻耗尽计时器,避免重复触发
            if (coyoteTimeCounter > 0)
            {
                coyoteTimeCounter = 0;
            }
        }
    }

    // 根据接地状态和剩余跳跃次数更新动画
    animator.SetBool("IsJumping", !isGrounded && currentJumpCount == 0);
}

关键逻辑说明

  • 缓冲跳跃:通过计时器记录离开地面后的窗口时间,在设定时长内仍允许触发跳跃,既解决了判定过严的问题,又不会出现靠墙误跳的情况。
  • 二次跳跃:通过currentJumpCount跟踪剩余跳跃次数,回到地面时重置次数,每次跳跃消耗一次次数,直到为0时无法再触发空中跳跃。
  • 跳跃时使用rb.velocity而非AddForce,能避免多次叠加力导致的跳跃高度异常,控制更精准。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.02 10:25:43