在HTML5游戏中用键切换暂停

时间:2014-06-18 14:26:02

标签: javascript html5 keydown keycode

我想使用键盘键 p 为html5游戏制作暂停和取消暂停的功能。我可以在按下 p 时暂停游戏,但在再次按 p 时不要取消暂停。我在这里做错了什么?

document.addEventListener('keydown', pauseGameKeyHandler, false);

function pauseGameKeyHandler(e) { 
    var keyCode = e.keyCode;
    switch(keyCode){ 
        case 80: //p
        togglePause();
        break; 
    }
}

function togglePause() {
    if ( paused = true ) {
        pauseTime = Date.now();
        var pausedElement = document.getElementById( 'paused' );

        if( pausedElement ) {
            pausedElement.style.width = world.width + 'px';
            pausedElement.style.height = world.height + 'px';
        }

        document.body.className = 'paused';
    } else if ( paused = false ) {
        var wasPaused = paused;
        paused = false;
        time += Date.now() - pauseTime;

        if( wasPaused ) {
            timeLastFrame = Date.now();
            animate();
        }

        document.body.className = '';
    }
}

2 个答案:

答案 0 :(得分:0)

if(paused = true)将变量paused设置为true - 因此,每次输入方法时,您都要将变量设置为true,因此您需要将==设置为if。永远不会取消你的游戏。在else ifif(paused)语句中使用双等号else if(!paused)。或者您可以说function togglePause() { if (paused) { // already paused // set the game state to paused } else if (!paused) { var wasPaused = paused; // you already know it will be set to false paused = false; // re-setting the game to paused... // restart the game... } } function togglePause() { if (paused) { // Already paused // restart the game! paused = false; // Game was restarted, so you're not paused anymore } else{ // Only other option is the game isn't paused, means currently playing // pause the game! paused = true; // Game was paused, so you're now paused } } ,以避免使用分配而非比较的错误。

此外,您的方法的整体逻辑似乎有点偏。这基本上就是你所拥有的。

{{1}}

它应该更像是

{{1}}

用于取消暂停和暂停的逻辑和代码应该添加到我只将其作为评论的位置。

答案 1 :(得分:0)

我找到了解决方案!

function pauseGameKeyHandler(e) { 
      var keyCode = e.keyCode;
      switch(keyCode){ 
        case 80: //p
          togglePause();
          break; 
      }
    }

    function togglePause(e) {
        if (keyCode == 80) {
            pause();
        } else if (!paused) {
            pause();
        } else if (paused) {
            resume();
        }
    };

    function pause() {
        paused = true;
        pauseTime = Date.now();

        var pausedElement = document.getElementById( 'paused' );

        if( pausedElement ) {
            pausedElement.style.width = world.width + 'px';
            pausedElement.style.height = world.height + 'px';
        }

        document.body.className = 'paused';
    }

    function resume() {
        var wasPaused = paused;

        paused = false;
        time += Date.now() - pauseTime;

        if( wasPaused ) {
            timeLastFrame = Date.now();
            animate();
        }

        document.body.className = '';
    }