Game Development Reference
In-Depth Information
Adding States and Switching Between Them
Now that you have your game-state manager, you can start adding different states to it. A very basic
game state is the title menu state. In the PenguinPairs3 example, you added a class TitleMenuState
to the application that represents this state. Because this state contains a couple of different game
objects, you let it inherit from the GameObjectList class. In the constructor of this class, you add
the game objects that are required for this state: a background and three buttons. You can reuse
the Button class that you developed earlier for the Jewel Jam game. Here is the constructor of
TitleMenuState :
function TitleMenuState(layer) {
GameObjectList.call(this, layer);
this.add(new SpriteGameObject(sprites.background_title,
ID.layer_background));
this.playButton = new Button(sprites.button_play, ID.layer_overlays);
this.playButton.position = new Vector2(415, 540);
this.add(this.playButton);
this.optionsButton = new Button(sprites.button_options, ID.layer_overlays);
this.optionsButton.position = new Vector2(415, 650);
this.add(this.optionsButton);
this.helpButton = new Button(sprites.button_help, ID.layer_overlays);
this.helpButton.position = new Vector2(415, 760);
this.add(this.helpButton);
}
Because you need to do something when a button is pressed, you have to override the handleInput
method. In that method, you check whether each of the buttons is pressed, and if so, you switch to
another state. For instance, if the player presses the Play Game button, you need to switch to the
level menu:
if (this.playButton.pressed)
GameStateManager.switchTo(ID.game_state_levelselect);
You add similar alternatives for the other two buttons. Now the title menu state is basically done.
In the PenguinPairs class, the only thing you need to do is make an instance of TitleMenuState and
add it to the game-state manager. You do the same thing for all the other states in the game. After that
you set the current state to be the title menu, so the player sees the title menu when the game starts:
ID.game_state_title = GameStateManager.add(new TitleMenuState());
ID.game_state_help = GameStateManager.add(new HelpState());
ID.game_state_options = GameStateManager.add(new OptionsMenuState());
ID.game_state_levelselect = GameStateManager.add(new LevelMenuState());
// the current game state is the title screen
GameStateManager.switchTo(ID.game_state_title);
 
Search WWH ::




Custom Search