Game Development Reference
In-Depth Information
p.initialize = function () {
canvas = document.getElementById('canvas');
stage = new createjs.Stage(canvas);
createjs.Ticker.setFPS(60);
createjs.Ticker.on('tick', this.onTick, this);
this.changeState(game.GameStates.MAIN_MENU);
}
window.game.OrbDestroyer = OrbDestroyer;
}(window));
The
initialize
method also sets up the ticker, and starts the game with the state
MAIN_MENU
, which will create
the main menu. Next, the state machine to make this work will be set up with a few functions, which will be used to
change the current state in the game (see Listing 10-17).
Listing 10-17.
OrbDestroyer.js - The Functions Used for Changing States
p.changeState = function (state) {
this.currentGameState = state;
switch (this.currentGameState) {
case game.GameStates.MAIN_MENU:
this.currentGameStateFunction = this.gameStateMainMenu;
break;
case game.GameStates.GAME:
this.currentGameStateFunction = this.gameStateGame;
break;
case game.GameStates.RUN_SCENE:
this.currentGameStateFunction = this.gameStateRunScene;
break;
case game.GameStates.GAME_OVER:
this.currentGameStateFunction = this.gameStateGameOver;
break;
}
}
p.onStateEvent = function (e, data) {
this.changeState(data.state);
}
There are four states in this exercise: two for the menu scenes, one for the game, and finally the
RUN_SCENE
state,
which will continuously run the current scene. All state functions are seen in Listing 10-18.
Listing 10-18.
OrbDestroyer.js - The State Functions that Run According to the Current Game State
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(this.currentScene);
this.currentScene = scene;
this.changeState(game.GameStates.RUN_SCENE);
}