Export (0) Print
Expand All

How to: Pause a Game

Demonstrates how to add 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.
  3. Add a variable to track the state of the pause key.
  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.
  5. Add a conditional around any update code so it will be called only if the game is not paused.
#region Using Statements
using System;
using System.Collections.Generic;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Audio;
using Microsoft.Xna.Framework.Content;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Input;
using Microsoft.Xna.Framework.Storage;
#endregion

public class Game1 : Microsoft.Xna.Framework.Game
{
    GraphicsDeviceManager graphics;
    ContentManager content;

    private bool paused = false;
    private bool pauseKeyDown = false;
    private KeyboardState keyboardState;
    private GamePadState gamePadState;

    public Game1()
    {
        graphics = new GraphicsDeviceManager( this );
        content = new ContentManager( Services );
    }


    protected override void Initialize()
    {
        // TODO: Add your initialization logic here.

        base.Initialize();
    }


    protected override void LoadGraphicsContent( bool loadAllContent )
    {
        if (loadAllContent)
        {
            // TODO: Load any ResourceManagementMode.Automatic content.
        }

        // TODO: Load any ResourceManagementMode.Manual content.
    }


    protected override void UnloadGraphicsContent( bool unloadAllContent )
    {
        if (unloadAllContent == true)
        {
            content.Unload();
        }
    }


    protected override void Update( GameTime gameTime )
    {
        gamePadState = GamePad.GetState( PlayerIndex.One );
        keyboardState = Keyboard.GetState();

        // Allows the default game to exit on Xbox 360 and Windows.
        if (gamePadState.Buttons.Back == ButtonState.Pressed)
            this.Exit();

        // TODO: Add your update logic here.
        checkPauseKey();
        if (paused == false)
        {
            base.Update( gameTime );

            Simulate();
        }

    }

    public void Simulate()
    {
        // Add game logic.
    }

    void checkPauseKey()
    {
        if (keyboardState.IsKeyDown( Keys.P ) || (gamePadState.Buttons.Y == ButtonState.Pressed))
        {
            pauseKeyDown = true;
        }
        else if (pauseKeyDown)
        {
            pauseKeyDown = false;
            paused = !paused;
        }
    }

    protected override void Draw( GameTime gameTime )
    {
        graphics.GraphicsDevice.Clear( Color.CornflowerBlue );

        // TODO: Add your drawing code here.

        base.Draw( gameTime );
    }
}
Show:
© 2014 Microsoft