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

Unity玩家移动脚本异常:设置maxJumps为1却能两次跳跃?

Unity玩家跳跃次数异常问题排查与修复

问题根源分析

你遇到的空中可跳2次(maxJumps设为1)的问题,主要来自两个核心原因:

  • 地面检测逻辑不可靠:依赖OnCollisionEnter2D/OnCollisionExit2D判断接地状态,容易因碰撞体多接触点、边缘摩擦等场景导致isGrounded误判,错误重置currentJumps为0,允许额外跳跃。
  • 浮点类型的精度隐患:maxJumps和currentJumps使用float类型,虽设置为1,但浮点运算的精度误差可能导致currentJumps < maxJumps的判断出现意外结果。

修复方案

1. 替换为可靠的地面检测逻辑

删除原有的OnCollisionEnter2D和OnCollisionExit2D方法,改用你已定义的groundCheck和groundLayer,通过Physics2D.OverlapCircle进行精准检测:

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

    // 替换原isGrounded判断逻辑,用地面检测点判断是否接地
    isGrounded = Physics2D.OverlapCircle(groundCheck.position, 0.2f, groundLayer);

    if (Input.GetButtonDown("Jump"))
    {
        jumpBuffer = maxJumpBuffer;
    }

    if (isGrounded)
    {
        currentJumps = 0; 
        coyoteTimer = coyoteTimerMax;
    }
    else
    {
        coyoteTimer -= Time.deltaTime;
    }

    jumpBuffer -= Time.deltaTime;

    if (jumpBuffer > 0 && coyoteTimer > 0 && currentJumps < maxJumps)
    {
        rb.velocity = new Vector2(rb.velocity.x, jumpingPower);
        currentJumps++;
        jumpBuffer = 0; // 成功跳跃后重置跳跃缓冲
    }

    if (Input.GetButtonUp("Jump") && rb.velocity.y > 0)
    {
        rb.velocity = new Vector2(rb.velocity.x, rb.velocity.y * 0.5f);
    }

    Flip();
}

注意:调整OverlapCircle的半径(示例中为0.2f)以匹配玩家碰撞体大小,确保groundCheck位于玩家脚部附近,且groundLayer正确选择地面所在图层。

2. 改用整数类型存储跳跃次数

将maxJumps和currentJumps改为int类型,彻底避免浮点精度问题:

public int maxJumps = 1;
private int currentJumps;

同时在Start方法中初始化跳跃次数(可选,但更严谨):

void Start()
{
    currentJumps = 0;
}

验证效果

修改后,地面检测会更精准,isGrounded状态不会误触发;整数类型的跳跃次数判断逻辑清晰,currentJumps达到maxJumps后会正确阻止空中额外跳跃,符合你设置的1次跳跃上限。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.17 17:30:41