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

Unity移动端长按跳跃实现更高跳跃功能的问题求助

修复移动端长按跳跃按钮的逻辑问题

你的问题核心很明确——原脚本里的速度削弱逻辑放错了位置:刚给角色施加初始跳跃速度,立刻就执行了rb.velocity.y * 0.5f,直接把起跳力砍了一半,而且长按跳跃的动态调整逻辑根本不该放在单次触发的Jump()方法里。

正确的思路是把跳跃逻辑拆成三部分:触发起跳、标记长按状态、在物理帧里动态调整跳跃高度。下面是修正后的完整方案:

public Rigidbody2D rb;
public Animator animator;
public float jumpPower = 8f;
public float holdJumpForce = 2f; // 长按期间的持续向上力,数值越大跳得越高
private bool isJumping = false;
private bool isHoldingJump = false;

// 绑定UI按钮的PointerDown事件(按下按钮时触发)
public void OnJumpDown()
{
    if (isGrounded())
    {
        isJumping = true;
        isHoldingJump = true;
        animator.SetBool("NowJumping", true);
        SoundManager.PlaySound("PlayerJump");
        // 施加初始跳跃力
        rb.velocity = new Vector2(rb.velocity.x, jumpPower);
    }
}

// 绑定UI按钮的PointerUp和PointerExit事件(松开/滑出按钮时触发)
public void OnJumpUp()
{
    isHoldingJump = false;
}

private void FixedUpdate()
{
    if (isJumping)
    {
        // 检测角色是否落地,重置跳跃状态
        if (isGrounded())
        {
            isJumping = false;
            animator.SetBool("NowJumping", false);
        }
        else
        {
            // 长按且角色处于上升阶段时,持续施加额外力提升跳跃高度
            if (isHoldingJump && rb.velocity.y > 0)
            {
                rb.AddForce(Vector2.up * holdJumpForce * Time.fixedDeltaTime, ForceMode2D.Impulse);
            }
            // 松开按钮时,立刻削弱上升速度,让跳跃提前结束
            else if (!isHoldingJump && rb.velocity.y > 0)
            {
                rb.velocity = new Vector2(rb.velocity.x, rb.velocity.y * 0.6f);
            }
        }
    }
}

// 你的地面检测逻辑,保持原有实现即可
private bool isGrounded()
{
    // 示例:用射线/碰撞器检测地面
    // return Physics2D.OverlapCircle(groundCheckTransform.position, 0.2f, groundLayerMask);
    return false;
}

关键修改说明

  1. 事件绑定调整:把原Jump()拆成OnJumpDown和OnJumpUp,分别对应按钮的按下、松开/滑出事件,确保长按状态被准确标记
  2. 逻辑分离:把动态调整跳跃高度的逻辑放到FixedUpdate中(物理更新帧,处理刚体逻辑更稳定)
  3. 条件判断优化:只有当角色处于上升阶段(y速度为正)时,才处理长按增益或松开放缓的逻辑,符合真实跳跃手感
  4. 移除错误逻辑:删掉了原脚本中刚起跳就削弱速度的代码,避免直接抵消初始跳跃力

注意事项

  • 一定要给UI按钮同时绑定PointerUp和PointerExit事件到OnJumpUp,防止玩家手指滑出按钮没触发松开逻辑
  • 调整jumpPower(初始跳跃力)和holdJumpForce(长按额外力)的数值,适配你的游戏手感
  • 确保isGrounded()方法正确实现,否则会出现多次起跳的问题

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.18 01:20:19