Export (0) Print
Expand All

How To: Pause a Game

Demonstrates how to add pause functionality to a game.

The Complete Sample

The code in this tutorial illustrates the technique described in the text. A complete code sample for this tutorial is available for you to download, including full source code and any additional supporting files required by the sample.

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. You should also pause when the Guide is active, as that will block user inputs from reaching the game.
    // Pause if the Guide is up, or if the user has paused
    if ((paused == false) && (Guide.IsVisible == false))
    {
        base.Update(gameTime);
    
        Simulate(gameTime);
    }
    

Community Additions

ADD
Show:
© 2014 Microsoft