Game Development Reference
In-Depth Information
There are various patterns when it comes to setting up a state machine, all slightly different, but all should
accomplish the same goal in managing state. In the approach I've decided to use in this topic, these game functions
will typically do one of two actions. When the state changes, a new scene should be initiated, while disposing of the
previous one. A scene is a collection of both code and visuals that should take over the screen when called upon to do
so. In EaselJS, this will most often be done within a custom container class.
The second type of action used in game state functions is to simply update the current scene. In the approach
used in this topic, the same function will be used for every scene that has been initiated, and will try to call a run
method on the current scene (see Listing 10-4). The tick event from the game loop is also passed into this run
method. The tick event carries useful properties that might be used within the game scene, such as delta and time .
You will be using these properties for the Space Hero game in Chapter 11.
Listing 10-4. A Run Scene State Will Run the Current Scene if Needed
function gameStateRunScene (tickEvent) {
if (currentScene.run) {
currentScene.run(tickEvent);
}
}
Not all scenes will need this type of constant updating, nor will it have a run method to execute, so this call will
be wrapped in a conditional. This RUN_SCENE state will be immediately set after a new scene has been created. Listing
10-5 shows an example of a game state function that is called on to start a new game.
Listing 10-5. An Example of a State Function Creating a New Scene
function gameStateGame () {
var scene = new game.Game();
stage.addChild(scene);
stage.removeChild(currentScene);
currentScene = scene;
changeState(game.GameStates.RUN_SCENE);
}
Notice that this state only exists for a single tick, and is used to simply change the current scene before changing
to the RUN_SCENE state.
Setting Up Game State Events
The changing of a state will most often be decided within the current running scene. This might happen from the click
of a button or the destruction of all lives in a game level. Similar to declaring game states, the game state events are
declared in the same fashion (see Listing 10-6).
Listing 10-6. Game State Event Ids Declared in an Object
var GameStateEvents = {
MAIN_MENU:'main-menu-event',
GAME_OVER:'game-over-event',
MAIN_MENU_SELECT:'game-menu-select-event',
GAME:'game-event',
SCORE_SCREEN:'score-screen-event'
}
 
Search WWH ::




Custom Search