Game Development Reference
In-Depth Information
Chapter 10
The State Machine and Scenes
A typical game will include multiple states during its existence. A state can be one of many different scenes in a game,
including a home screen, a leaderboard, a settings menu, the game itself, and many others. A game can consist of
a few or many states, and the management system to assure that only one state is running at a time is an important
technique in game development. The collective components that make up this management system are referred to as
a state machine .
This chapter will take a close look at each area that makes up a state machine, and then you'll put your new
knowledge into practice by creating a simple game that will implement one. This game will consist of a title
screen, the game level, and a game over screen. These scenes will all be written outside of the global scope, which
will provide better code structure, but will introduce more of those pesky scope issues. I will further address
those issues in this chapter.
Deconstructing a State Machine
So far, the games in this topic have all been built within one screen. In other words, they have had only one state
during the entire game. The Break-It game in Chapter 4 used a Boolean variable to determine if the game was in play;
if not, it fell into a waiting state for the user to take action. This approach is a simple technique to manage state, but it's
not practical once you start tacking on more states and scenes to your game. This section will break down the process
of building a state machine to properly run and manage your game scenes.
Declaring States
States are typically stored in constants that can easily be accessed and readable within the code of your game. This
approach was used in Chapter 9 when declaring assets in an asset manager. These values will be used to determine
what state the game should switch to or continue to run in. Listing 10-1 shows an example of a few states being
declared and stored inside an object.
Listing 10-1. Example of State Ids Being Declared
var GameStates = {
MAIN_MENU:0,
RUN_SCENE:10,
GAME:20,
GAME_OVER:30
}
 
Search WWH ::




Custom Search