Phaser allows us to create a variety of time driven events, in a simple and intuitive way.
time.events.add(tick, callback, callbackContext) adds a timer event which will execute callback function in the callbackContext context after tick time has passed.
Phaser.Timer.SECOND is a Phaser reserved variable which means “one second”, checkTiles is the name of the function we are going to call after a second we realized the player uncovered two tiles. The use of this should now clearly suggest you how to declare checkTiles function.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
showTile: function(target) { if(selectedArray.length < 2 && selectedArray.indexOf(target) == -1) { target.frame = target.value; selectedArray.push(target); if(selectedArray.length == 2) { game.time.events.add(Phaser.Timer.SECOND, this.checkTiles, this); } } }, checkTiles: function() { // function code goes here } |
What should we write in checkTiles function?
Exactly the same code we used for checking tiles when there is a match and remove/cover them.
1 2 3 4 5 6 7 8 9 10 11 |
checkTiles: function(){ if(selectedArray[0].value == selectedArray[1].value) { selectedArray[0].destroy(); selectedArray[1].destroy(); } else { selectedArray[0].frame = 10; selectedArray[1].frame = 10; } selectedArray.length = 0; } |
Now run the game, and you will see the game waits a second with both tiles shown on the stage before removing or covering back them. Now, the last – but not least – difference between our game and a real Concentration game: our tiles are always placed in the same, predictable, place. We have to spice up a bit the game by shuffling the tiles.
Download Source
File: using-timers-to-schedule-events.zip
Next Tutorial →
← Previous Tutorial
Checking for successful matches and removing tiles or turning them back