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

Unity 2D平台游戏垂直跳跃失效:Input.GetKeyUp()偶现异常

Unity 2D平台跳跃失效问题修复

问题根源分析

从你提供的代码来看,跳跃逻辑存在两个核心问题:

  1. 按住W时强制清零全轴速度:rigidBody.velocity = new Vector2(0, 0);会同时清空x轴侧向移动和y轴速度,不仅破坏侧向移动功能,还可能在蓄力阶段持续抑制角色的速度变化,导致松开W时设置的跳跃速度被干扰。
  2. 缺少地面检测判断:没有限制只有角色在地面时才能触发跳跃,若角色在空中触发,重力会瞬间抵消跳跃速度,表现为“跳不起来”。

具体修复方案

1. 修正蓄力阶段的速度处理逻辑

保留x轴侧向移动速度,仅清零y轴速度(确保蓄力时角色在地面静止):

if (Input.GetKey(KeyCode.W))
{
    // 只保留侧向移动速度,清零y轴避免蓄力时角色浮空
    rigidBody.velocity = new Vector2(rigidBody.velocity.x, 0);
    if (jumpSpeed < 10f)
    {
        // 简化条件判断写法
        jumpSpeed += Time.deltaTime * (Bossfight.bossfightStarted ? 8 : 4);
    }
}

2. 添加地面检测与跳跃触发限制

首先在脚本中定义地面检测相关变量:

// 地面检测点(建议放在角色脚底位置)
public Transform groundCheck;
// 检测范围半径
public float checkRadius = 0.2f;
// 指定地面所在的图层
public LayerMask groundLayer;
private bool isGrounded;

然后在FixedUpdate中执行地面检测,并重置音效标记:

void FixedUpdate()
{
    // 检测角色是否接触地面
    isGrounded = Physics2D.OverlapCircle(groundCheck.position, checkRadius, groundLayer);
    // 回到地面后允许再次播放跳跃音效
    if (isGrounded)
    {
        isPlaying = false;
    }
}

最后修改跳跃触发逻辑,仅在地面时生效:

if (Input.GetKeyUp(KeyCode.W) && isGrounded)
{
    rigidBody.velocity = new Vector2(rigidBody.velocity.x, jumpSpeed);
    jumpSpeed = Bossfight.bossfightStarted ? 7f : 5f;
    
    if (!isPlaying)
    {
        hunterJump.Play();
        isPlaying = true;
    }
}

3. 检查Rigidbody2D配置

  • 确认Body Type设置为Dynamic,否则velocity修改不会生效。
  • 调整Gravity Scale至合理值(建议1-3),避免重力过大直接抵消跳跃速度。
  • 排查其他脚本是否在修改rigidBody.velocity,防止覆盖跳跃逻辑。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.04 18:32:44