The game mecanic of collecting keys to be able to open doors to ender other spaces is well used in platform games to increase a sense of adventure.
Let's look at one way to do this. We draw on the code of a similar tutorial here by Belen Albeza 1.
There is some background knowledge in this book that will be useful for us in getting this mechanic to work;
As mentioned a lot of these example is covered by the Game Mechanic: Adding Levels - please have a look at that one first.
Note these variables at the start of our code that are located here as they are needed by more than one function;
var wlevel = 1;
var hasKey = false;
We start the game at level one and in a state where our player doesn't have the key
Then we create some data in the json style format for our two different levels which features a location for our key and door and then loop through them to generate the sprites on our game stage.
Then when the play is happening. We want to set up overlap conditions in our update function for player and keys and doors.
game.physics.arcade.overlap(player, key, playState.hitKeys);
game.physics.arcade.overlap(player, door, playState.hitDoors);
We then create the functions mentioned. For hitKeys we want to kill off the key and set our hasKey variable to true, ready to open the door.
playState.hitKeys = function (player, key) {
key.kill();
hasKey = true;
};
For the hitDoor function we need to check to see if the player has already picked up the key, as we don't want anything to happen if that is not the case.
playState.hitDoors = function (player, door) {
if (hasKey === true){
door.animations.play("open");
hasKey = false;
game.time.events.add(1000, playState.nextLevel, this);
}
};
If the player does have the key then we want to play the animation of the door opening, then reset teh value of hasKey as we don't want that to continue to the next level, and then call the next level function after one second so that we get to see the door openting. ]
The nextLevel function has two conditions, if we are on level 1 then go then increase the wlevel value by one and restart the game with this new value so that the next level loads up.
playState.nextLevel = function(){
if (wlevel < 2){
wlevel += 1;
game.state.start("play", true, false, wlevel);
}
else {
wlevel = 1;
game.state.start("play", true, false, wlevel);
}
};
Or if anything else is the case, then we are on level 2, so reset to level one before restarting.
That's about it. We hope you enjoy adding this game dynamic to your game to jump on enemies.
There has been error in communication with Booktype server. Not sure right now where is the problem.
You should refresh this page.