Pause Functionality
June 22, 2009 5:11 AMHow To: Pause a Game
Demonstrates how to add pause functionality to a game.
The Complete Sample
The code in this topic shows you the technique. You can download a complete code sample for this topic, including full source code and any additional supporting files required by the sample.
Adding Pause Functionality to a Game
To add pause functionality to a game
-
Derive a class from Game.
-
Add a variable to track the pause state.
C#private bool paused = false;
-
Add a variable to track the state of the pause key.
C#private bool pauseKeyDown = false;
-
Add a function to poll the state of the pause key with Keyboard.GetState and KeyboardState.IsKeyDown.
If the key has changed from down to up, toggle the pause state.
C#private void checkPauseKey(KeyboardState keyboardState, GamePadState gamePadState){ if (keyboardState.IsKeyDown(Keys.P) || (gamePadState.Buttons.Y == ButtonState.Pressed)) { pauseKeyDown = true; paused = true; } else if (pauseKeyDown) { pauseKeyDown = false; paused = false; }}
-
Add a conditional around any update code so it will be called only if the game is not paused.
C#// Pause if the Guide is up, or if the user has pausedif ((paused == false) && (Guide.IsVisible == false)){ base.Update(gameTime); Simulate(gameTime);}
Categorised in: Programming