Game Development Reference
In-Depth Information
As you can see when you look at the last instruction in the method, you return the index of the game
state in the array. You do this because later it will provide you with a simple way to find the game
state you added. You store this index as an identifier value in the ID variable. For example, adding a
title menu state and storing its ID after you add it can be done in a single line of code, as follows:
ID.game_state_title = GameStateManager.add(new TitleMenuState());
Because the game-state identifier corresponds exactly to the index of the game state in the array,
you can write a very simple get method that retrieves a game state, given an ID:
GameStateManager_Singleton.prototype.get = function (id) {
if (id < 0 || id >=this._gameStates.length)
return null;
else
return this._gameStates[id];
};
Switching to another game state is also straightforward. This is done by calling the switchTo method:
GameStateManager_Singleton.prototype.switchTo = function (id) {
this._currentGameState = this.get(id);
};
Handling the different game-loop methods is quite simple. You have to call them on the currently
active game state. For example, the handleInput method of GameStateManager is as follows:
GameStateManager_Singleton.prototype.handleInput = function (delta) {
if (this._currentGameState !== null)
this._currentGameState.handleInput(delta);
};
You follow a similar procedure for the other game-loop methods. To make the game-state manager
an integral part of the game, you call its game-loop methods in the Game.mainLoop method:
Game_Singleton.prototype.mainLoop = function () {
var delta = 1 / 60;
GameStateManager.handleInput(delta);
GameStateManager.update(delta);
Canvas2D.clear();
GameStateManager.draw();
Keyboard.reset();
Mouse.reset();
Touch.reset();
requestAnimationFrame(Game.mainLoop);
};
 
Search WWH ::




Custom Search