Pause Functionality

June 22, 2009 5:11 AM Published by
How 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

  1. Derive a class from Game.

  2. Add a variable to track the pause state.

    	private bool paused = false;
    	
  3. Add a variable to track the state of the pause key.

    	private bool pauseKeyDown = false;
    	
  4. 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.

    	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;    }}
    	
  5. Add a conditional around any update code so it will be called only if the game is not paused.

    	// Pause if the Guide is up, or if the user has pausedif ((paused == false) && (Guide.IsVisible == false)){    base.Update(gameTime);    Simulate(gameTime);}
    	

Categorised in:


Tag Cloud