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

Unity游戏中如何防止玩家落地自动跳跃(兔子跳)问题

解决跳跃连跳问题:必须松开跳跃键才能再次起跳

当前问题:玩家落地时若持续按住跳跃键,角色会自动触发再次跳跃,不符合「必须松开按键后才能再次起跳」的需求。

修改方案

核心思路是新增一个状态变量,追踪跳跃键是否完成「按下-松开」的循环,避免落地时直接触发跳跃:

  • 添加hasJumpBeenReleased变量,初始值设为true(游戏启动时按键未按下,默认满足松开状态)
  • 在跳跃键松开的回调中,标记hasJumpBeenReleased为true
  • 触发跳跃的条件,同时验证jumpIsPressed和hasJumpBeenReleased,触发后立即将hasJumpBeenReleased设为false

修改后的代码

public class GenesisPhysics : MonoBehaviour {
    public bool isGrounded = true;
    public bool jumpIsPressed;
    private bool hasJumpBeenReleased = true; // 新增变量:标记跳跃键是否已松开
    public IA inputActions;  // New input system's Input Action Asset C# class
    
    private void Awake()
    {
        inputActions = new IA();
        
        // Movement actions stuff...

        inputActions.PlayerControls2D.Jump.performed += jumpContext => jumpIsPressed = true;
        inputActions.PlayerControls2D.Jump.canceled += jumpContext => {
            jumpIsPressed = false;
            hasJumpBeenReleased = true; // 松开按键时标记已释放
        };
    }
    
    private void FixedUpdate() 
    {
        if(isGrounded) 
        {
            ExecuteGroundStateLoop();

        } else {
            ExecuteAirStateLoop();
        }
    }

    private void ExecuteGroundStateLoop() 
    {
        // Do stuff...
    
        if(jumpIsPressed && hasJumpBeenReleased) { // 同时检查两个条件
            isGrounded = false;
            hasJumpBeenReleased = false; // 触发跳跃后,标记未释放
            // Set x and y speeds to be applied in Air state
        } else {
            // Do some more stuff...
        }
    }
    
    private void ExecuteAirStateLoop()
    {
         // Applying gravity, jump force, checking for ground and other stuff...
         
         // If ground is found, set isGrounded to true.
    }

    void OnEnable()
    {
        inputActions.Enable();
    }

    void OnDisable()
    {
        inputActions.Disable();
    }
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.22 14:39:15