Phaser for Beginners

Preloading images

One of the worst things you can do in the making of a game is to handle graphic assets before you actually loaded them. That’s why we will need to preload the sprite sheet. Let’s add a couple of lines to game.js:

What happened now?

We preloaded the sprite sheet we created some minutes ago. Let’s see the new
lines of code:

Do you remember we created the sprite sheet where each tile is an 80×80 pixels square?

We are going to refer to that number a lot of times in the making of the game,
each time we will need to know the size of a tile. Rather than filling the source code with a series of “80” scattered here and there, we are going to store this value in a variable called tileSize.

Not only our source code will be more readable, but above all it will be a lot easier to make changes to the game should we decide to change the size of the tile to, let’s say, 60 or 100. No more “search and replace” operations, but a single value to change.

Also, notice the variable has been placed inside the window.onLoad function: this way we will be able to access to it from all functions declared inside window.onLoad function, and of course in window.onLoad function itself.

In JavaScript, variables are only recognized inside their functions, and in functions inside their functions. Variables are created when a function starts, and deleted when the function is completed. The part of a script where a variable is recognized is called scope.

Now, it’s time to introduce another Phaser function to be placed inside a state.

preload function, as the name suggests, is executed when the state preloads, and of course it will run before create function. Since we are going to start the game itself in create function, it’s obvious we will need to preload all stuff in preload function.

And finally, here’s how we load a sprite sheet. From now on, the sprite sheet is stored somewhere into the memory dedicated to the game, and we can access it whenever we need it.

load.spritesheet(key, url, frameWidth, frameHeight) loads a sprite sheet and wants as arguments respectively the unique asset key of the sheet file, the URL of the sheet file, the width of each single frame and the height of each single frame.

In our example it works this way:

  • tiles is the name we want to give to this sprite sheet. From now on, we will refer to it as “tiles”.
  • tiles.png is the name of the image we are using for the sprite sheet.

The remaining two tileSize arguments represent respectively the width and the height of tiles, in pixels. We composed a sprite sheet image, and we loaded into our Phaser game. It’s time to display it on the screen.

Download Source

File: preloading-images.zip


Next Tutorial →

Placing images on the stage

← Previous Tutorial

Creating tile graphics using a sprite sheet