Game Development Reference
In-Depth Information
The states listed in this object can now be access in following way:
currentGameState = GameStates.MAIN_MENU;
The state machine will most often run within the main class of your application, and will be used to load and
unload scenes. The current state of the application will be held in a variable so it can be accessed at any time.
Setting the Game State
The game state is typically set within a function that is called when the state should change. It should accept a
parameter, which will be used to set the new game state. This function will also contain a switch statement to evaluate
the current state and appropriately change the game's behavior.
The behavior of the game is determined by the function that will run on each tick of the game loop. This function
should also be stored in a variable so it can be continuously called while the game is running. Listing 10-2
demonstrates an example of this important function.
Listing 10-2. A State Machine Function, Used for Changing Game State
function changeState (state) {
currentGameState = state;
switch (currentGameState) {
case GameStates.MAIN_MENU:
currentGameStateFunction = gameStateMainMenu;
break;
case GameStates.GAME:
currentGameStateFunction = gameStateGame;
break;
case GameStates.RUN_SCENE:
currentGameStateFunction = gameStateRunScene;
break;
case GameStates.GAME_OVER:
currentGameStateFunction = gameStateGameOver;
break;
}
}
//change game state
changeState(GameStates.GAME_OVER);
Running the Game
When the game state and game state functions have been set, the game loop will react by firing the current game state
function. Listing 10-3 creates the ticker handler, which will call the current game state function before updating the stage.
Listing 10-3. The Current Game State Function Is Called Within Each tick Event
createjs.Ticker.on('tick', onTick);
function onTick(e){
currentGameStateFunction(e);
stage.update();
}
 
Search WWH ::




Custom Search