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

Unity 2D跳跃系统中Input.GetKeyUp()无法正常触发问题求助

问题根源

Input.GetKeyUp()是单帧触发的输入事件,而FixedUpdate()是按固定时间间隔执行(默认0.02秒),如果按键抬起的瞬间刚好卡在两次FixedUpdate执行之间,这个输入信号就会被错过,导致随机失效。所有输入检测逻辑都应该放在Update()中,因为它和游戏帧同步,不会遗漏输入事件。

修复方案

把输入检测部分移到Update(),物理操作留在FixedUpdate(),用布尔变量传递输入状态:

private bool isJumpHeld;
private bool shouldCancelJump;

void Update()
{
    // 输入检测和帧同步,避免错过信号
    if (Input.GetKeyDown(jump))
    {
        isJumpHeld = true;
    }
    if (Input.GetKeyUp(jump))
    {
        isJumpHeld = false;
        shouldCancelJump = true;
    }
}

void FixedUpdate()
{
    Jump();
}

void Jump()
{
    if (shouldCancelJump)
    {
        jumpTimer = 0;
        canJump = false;
        shouldCancelJump = false; // 重置标志位
    }
    
    if (isJumpHeld && canJump && jumpTimer > 0)
    {
        jumpTimer--;
        rb.velocity = new Vector2(rb.velocity.x, 0f);
        jumpVector = Vector2.up * jf * 200f;
        rb.AddForce(jumpVector);
    }
    
    if (grounded && rb.velocity.y <= 0)
    {
        jumpRefresh();
    }
}

void jumpRefresh()
{
    canJump = true;
    jf = jumpForce;
    jumpTimer = timerConstant;
    isJumpHeld = false; // 落地时重置跳跃状态
    shouldCancelJump = false;
}
额外优化建议
  • 可以改用Input.GetButtonUp("Jump")替代自定义的jump按键变量,符合Unity输入系统规范,后续调整按键设置更方便。
  • 检查grounded的检测逻辑是否可靠,比如用Physics2D.Raycast或碰撞器触发事件实现,避免因落地判断延迟导致的跳跃状态异常。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.01 06:10:04