jQuery:暂停按钮可以暂停所有其他操作

jQuery: Pause button to pause all other actions

本文关键字:暂停 其他 操作 按钮 jQuery      更新时间:2023-09-26

我正在制作一个小游戏,我有一个暂停游戏的按钮。我怎么能"暂停"游戏不做任何动作,但当点击"恢复"只是恢复所有动作时,就好像什么都没发生一样?

假设我有一些复杂的编码,所以我不能只在一个函数中实现一件小事:它确实需要覆盖所有"繁忙"的事情。

感谢您抽出时间!

暂停按钮:

function pauseGameBtn() {
    $("#pause").click(function() {
        if (pauseBtnClicked == true) {
            // ...
        }
        else {
            // ...
        } 
    });
}

一个典型的游戏循环通过一个代码点。你的计时器会定期调用它,并且是你需要检查暂停状态的唯一地方。

这被大大简化了,但基本思想是:

var paused = false;
// endless game loop
setInterval(function(){
    if (!paused){
       RunGameLoop();  // process input => calculate => render etc
    }
}, 50);
$("#pause").click(function() {
     paused = true;
});
$("#resume").click(function() {
     paused = false;
});

伪:

var  itv = null; // The interval
(function gameUIlogic{}(
   // Main Menu stuff
   // and other stuff independent from framerate interval
)());
function gameLogic() {
    // Game logic here
    itv = window.requestAnimationFrame(loop);
}
function pause() {
    return itv ? (window.cancelAnimationFrame(itv ), itv=null) : gameLogic();
}

假设您有一个播放和暂停按钮,只需在两者上触发pause()功能即可。