A Simple Way to Pause Your Game
Pausing your game is a nice feature to give the user (and this idea can be expanded to include in-game menus) and it turns out to be a very easy to implement feature too.
First, we will add an enumerator list with the items Normal and Paused.
enum GameStates
{
Normal,
Paused,
}
You then need to create a variable that will store these values.
GameStates GameState;
In the update method of your game loop, you will need some way to toggle between the two states (Normal and Paused). We will use the "P" key for this example. In addition, we will add some extra code to make sure that at least a little time has passed before a "P" key press can be registered a second time. If you don't include this code, your game will pause/unpause multiple times with each key press.
float KeyPressCheckDelay = 0.25f;
float TotalElapsedTime = 0;
protected override void Update(GameTime gameTime)
{
// Needed for keyboard events
float elapsed = (float)gameTime.ElapsedGameTime.TotalSeconds;
TotalElapsedTime += elapsed;
ksKeyboardState = Keyboard.GetState();
// Normal game loop
if (GameState == GameStates.Normal)
{
// Do your normal game logic here.
if (TotalElapsedTime >= KeyPressCheckDelay)
{
// Pause the current game
if (ksKeyboardState.IsKeyDown(Keys.P))
{
GameState = GameStates.Paused;
fTotalElapsedTime = 0.0f;
}
}
}
// Game is paused.
else
{
if (TotalElapsedTime >= KeyPressCheckDelay)
{
// UnPause the current game
if (ksKeyboardState.IsKeyDown(Keys.P))
{
GameState = GameStates.Normal;
fTotalElapsedTime = 0.0f;
}
// Do any other fun stuff you want to do while the game is paused.
}
}
base.Update(gameTime);
}
Since none of your game variables are being updated, you don't have to change anything in the draw method for this to work. Your game will continue to draw the scene exactly as it was when it was paused. On the game I am developing now, this creates a neat effect as enemies still animate but do not move.
You could easily add a check to the draw method in the event that you wanted to do something special when paused, like create an in-game menu. You could use this GameState enum for other things as well, like splash screens, cut scenes, and credits.
This article has been view 5279 times.
|