Phaser for Beginners

Adding interactivity to images by turning them into clickable and touchable buttons

As you know we are going to build a cross platform game. This means it has to run properly on each device, from desktop computers to smart phones and tablets. Unfortunately, different devices use different ways to let the player interact with the game: in our case, on desktop computers players will click on a tile with the mouse to select it, while on a smart phone a tile will be selected with a touch.

Do we have to check for both mouse clicks and finger touches? No, because Phaser handles everything internally, letting us focus on the game itself. To give tiles the capability of being clicked or touched, we have to turn them into buttons. Time to edit placeTiles function once more:

When you use a button rather than an image, interactivity is automatically added by Phaser.

add.button(x, y, key, callback, callbackContext) adds a button at coordinates ( x , y ) using the image stored with key value. callback is the function to call when the button is pressed. callbackContext is the context in which the callback will be called, is usually this because it’s a reference to the object that owns the currently executing code.

Looking at the syntax of button creation, you can see we have to add a function called showTile , and the presence of this suggests it’s another method of playGame object.

We don’t want showTile function to do that much at the moment, so we are just showing a message in the console. Run the game, click on any tile and see what happens:

Thanks to Phaser, turning an image into an interactive element was really easy, but now a difficult task awaits us: we have to turn a button into something more complex. Since each button represents a tile, we will need to store the value of each tile – which is the symbol to be shown when we turn it – somewhere.

Download Source

File: turning-tile-into-clickable-and-touchable-buttons.zip


Next Tutorial →

Giving each button a custom property and accessing it when touched/clicked

← Previous Tutorial

Displaying given frames in a sprite sheet

Leave a Reply

Your email address will not be published. Required fields are marked *