Difference between revisions of "Game states"
Line 13: | Line 13: | ||
<syntaxhighlight lang=csharp> | <syntaxhighlight lang=csharp> | ||
− | GameState state; | + | GameState state = GameState.MainMenu; |
</syntaxhighlight> | </syntaxhighlight> | ||
Revision as of 08:28, 30 September 2017
A simple way to get started with different states in the game is to use a simple state machine. Declare an enum with the different game states.
enum GameState
{
MainMenu,
Gameplay,
EndOfGame,
}
In your Game class, declare a member of the GameState type.
GameState state = GameState.MainMenu;
In your Update() method, use the _state to determine which update to run.
void Update(GameTime gameTime)
{
base.Update(gameTime);
switch (state)
{
case GameState.MainMenu:
UpdateMainMenu(gameTime);
break;
case GameState.Gameplay:
UpdateGameplay(gameTime);
break;
case GameState.EndOfGame:
UpdateEndOfGame(gameTime);
break;
}
}
Now define the UpdateMainmenu(), UpdateGameplay() and UpdateEndOfGame().
void UpdateMainMenu(GameTime gameTime)
{
// Respond to user input for menu selections, etc
if (pushedStartGameButton)
state = GameState.GamePlay;
}
void UpdateGameplay(GameTime gameTime)
{
// Respond to user actions in the game.
// Update enemies
// Handle collisions
if (playerDied)
state = GameState.EndOfGame;
}
void UpdateEndOfGame(GameTime gameTime)
{
// Update scores
// Do any animations, effects, etc for getting a high score
// Respond to user input to restart level, or go back to main menu
if (pushedMainMenuButton)
state = GameState.MainMenu;
else if (pushedRestartLevelButton)
{
ResetLevel();
state = GameState.Gameplay;
}
}
In the Game.Draw() method, again handle the different game states.
void Draw(GameTime gameTime)
{
base.Draw(gameTime);
switch (state)
{
case GameState.MainMenu:
DrawMainMenu(gameTime);
break;
case GameState.Gameplay:
DrawGameplay(gameTime);
break;
case GameState.EndOfGame:
DrawEndOfGame(gameTime);
break;
}
}
Now define the different Draw methods.
void DrawMainMenu(GameTime gameTime)
{
// Draw the main menu, any active selections, etc
}
void DrawGameplay(GameTime gameTime)
{
// Draw the background the level
// Draw enemies
// Draw the player
}
void DrawEndOfGame(GameTime gameTime)
{
// Draw text and scores
// Draw menu for restarting level or going back to main menu
}