Game Development Reference
In-Depth Information
Because the base of each scene will most likely extend a display object, dispatching events is a great way to
communicate back to the main application that something needs to happen. Listing 10-7 shows an example of this
being done within a game menu screen.
Listing 10-7. A Button that Dispatches a State Event
function onStartButton(e){
dispatchEvent(GameStateEvents.GAME);
}
This example demonstrates the action that happens when a player clicks a button to play the game. Because this
menu resides in a container class, dispatching this event is possible. Back in the state function that added this menu
screen is where the listener is set up (see Listing 10-8).
Listing 10-8. Setting a State Event Listener on a New Scene
p.gameStateMainMenu = function () {
var scene = new game.GameMenu();
scene.on(game.GameStateEvents.GAME, this.onStateEvent, this, false,
{state:game.GameStates.GAME});
stage.addChild(scene);
stage.removeChild(currentScene);
this.currentScene = scene;
this.changeState(game.GameStates.RUN_SCENE);
}
The changeState function is written to be called from anywhere by passing it the state you wish to change to.
In the case of an event, a handler function needs to be set up as an intermediate step in the state changing process.
By utilizing the on method to listen for these events, an object can be passed into the handler. You'll also notice the
use of the third parameter, which is used to keep the scope to this within the handler function. You used this same
approach with PreloadJS when building the asset manager in Chapter 9.
in order to reach the fifth parameter in the on method, you need to fill out all proceeding options, even if you
don't need them. this is done in most cases by simply assigning the default value for all properties you need to bypass.
Note
A generic object is created as the data you wish to pass into the onStateEvent function. The object will contain
one property, state , and will hold the value of the state you wish to change to. Listing 10-9 shows this intermediate
function for state changing.
Listing 10-9. The Handler Function for All State Events
function onStateEvent (e, data) {
this.changeState(data.state);
}
The first parameter of any event handler will be the event object that invoked it. This object is not needed in this
case, but must be entered so the second parameter can be declared and accessed.
This concludes the major components of a working state machine. The next exercise, Orb Destroyer, will fully
utilize these procedures to build a state machine for a simple game.
 
 
Search WWH ::




Custom Search