Search icon
Arrow left icon
All Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Newsletters
Free Learning
Arrow right icon
SDL Game Development

You're reading from  SDL Game Development

Product type Book
Published in Jun 2013
Publisher Packt
ISBN-13 9781849696821
Pages 256 pages
Edition 1st Edition
Languages
Author (1):
Shaun Mitchell Shaun Mitchell
Profile icon Shaun Mitchell

A simple way for switching states


One of the simplest ways to handle states is to load everything we want at the game's initialization stage, but only draw and update the objects specific to each state. Let's look at an example of how this could work. First, we can define a set of states we are going to use:

enum game_states
{
  MENU = 0,
  PLAY = 1,
  GAMEOVER = 2
};

We can then use the Game::init function to create the objects:

// create menu objects
m_pMenuObj1 = new MenuObject();
m_pMenuObj1 = new MenuObject();

// create play objects
m_pPlayer = new Player();
m_pEnemy = new Enemy();

// create game over objects…

Then, set our initial state:

m_currentGameState = MENU;

Next, we can change our update function to only use the things we want when in a specific state:

void Game::update()
{
  switch(m_currentGameState)
  {
    case MENU:
      m_menuObj1->update();
      m_menuObj2->update();
      break;

    case PLAY:
      m_pPlayer->update();
      m_pEnemy->update();

    case GAMEOVER...
lock icon The rest of the chapter is locked
Register for a free Packt account to unlock a world of extra content!
A free Packt account unlocks extra newsletters, articles, discounted offers, and much more. Start advancing your knowledge today.
Unlock this book and the full library FREE for 7 days
Get unlimited access to 7000+ expert-authored eBooks and videos courses covering every tech area you can think of
Renews at $15.99/month. Cancel anytime}