简体   繁体   中英

Having trouble adding a pause function on javascript game

I am trying to figure out how when the page loads the game is "paused" and the user has to hit enter to play and when the user does so the game starts.

Here are the current keystates to control the player when the game is active. I feel like I'm almost there (correct me if I'm wrong), but I just can't get what makes the canvas "pause" when the page is loaded and how to make it "play" when the enter button is pushed.

keystate = {};
  document.addEventListener('enter', function(evt){
    keystate[evt.keyCode] = true;
  });
  document.addEventListener('keydown', function(evt){
    keystate[evt.keyCode] = true;
  });
  document.addEventListener('keyup', function(evt){
    delete keystate[evt.keyCode];
  });

I have two ways,

  • One simple, but not so nice

  • One hard, can be nice

The first ay is just alerting something with comfirm(text) .

Here is the code for that way :

 var gameBrightness = 10; function pause() { var pause = confirm("You paused the game, click 'OK' to continue your game and the other button to go to options"); if (pause == false) { //Didn't click on OK var options = confirm("Click on 'Ok' to not change brigthness, but the other one to change the brightness to a random value"); if (options == true) { //Clicked on OK ReDopause(); return; } else { //Didn't click on OK brightness = Math.floor(Math.random() * 20); document.getElementById("brightness").innerHTML = brightness; ReDopause(); return; } } } var ReDopause = function() { pause(); } 
 <button onclick="pause()">Pause</button> <span id="brightness">brigthness : 10</span> 

The second way I havn't made but it is in each movements or timers add an if statment. Like this:

var pause = false;
setInerval(tick, 100);

function tick() {
  if (pause == false) {
     ....
  }
}

At the bginnning you should have a canvas which isn't visible which is the pause menu. Here gow you do the CSS for that:

#pause {
  display: none;
  ...
}

When you pause set pause to true , set your main canvas to document.getElementById("mainCanvas").style.display = "none" this will make the canvas dissapear but still with all it's drawings. Then show the pause canvas like this : document.getElementById("mainCanvas").style.display = "initial" . The when "Continue" is clicked: set pause to false and to the contrary of this.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM