Button press to pause game

I have a student who wants to code a space bar press to pause the game and then press it again to restart it.

One idea would be to use a modulus inside of an if statement. Create a variable to count the number of times you press space bar and set the value to 0.

var counter = 0;

Create an if statement to count the number of times you press the space bar.

if(keyWentDown(“space”)) {
counter = counter + 1;
}

Create another if statement to pause the game (stop whatever actions you are doing) if counter mod 2 is not equal to 0 . So every odd number of space bar presses should pause the game.

SAMPLE CODE FOR THE FLYER GAME

if(counter % 2 != 0) {
character.velocityX = 0;
character.velocityY = 0;
fill(“black”);
textSize(“50”);
textAlign(“center”, “center”);
text(“PAUSED”,200,200);
}

Hope this helps!

1 Like

I was trying to work out some kind of clever workaround using booleans, but @mmathes beat me to the punch. That looks like it should work.

–Michael K.

1 Like