Phaser for Beginners

Adjusting assets placement according to stage size

Placing assets according to game size is really easy, once you know game size. If you look at game declaration, you can see its width and height are 500 pixels, but let’s suppose we don’t know it, or we want to have the freedom to modify game size by changing only its declaration, without any further search/replace. Phaser gives us some properties to get the width and height of a Phaser Game instance.

A property of an object is a value associated to a variable within the object itself. Usually properties can be read and written, but some of them can only be read.

So we are adding a couple of lines to placeTiles function:

Let’s have a look at how we determined the value of leftSpace, which is basically the left offset used to place tiles:

We subtract to game width the length of all tiles ( numCols * tileSize ) and the length of all empty spaces between two tiles ( (numCols – 1) * tileSpacing ) getting the difference between game width and the width actually used by the tiles. Dividing this difference by two we can find the amount of pixels to move to the left each tile to have the board centered on the game stage.

width and height properties return width and height of a Phaser Game instance.

The same concept applies to vertical offset. Launch the game now:

Now we have our tile board centered in the game stage thanks to two game properties. Anyway, shouldn’t the tiles start as covered, that is showing the question mark? It seems we are only able to show the first frame of our sprite sheet. Let’s show images properly.

Download Source


Next Tutorial →

Displaying given frames in a sprite sheet

← Previous Tutorial

Setting up the game field

Leave a Reply

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