Phaser: Adding images

By

Learn how to add images in Phaser by preloading them in preload, then placing them with this.add.image and adjusting origin, scale, and flip.

~~~

This post is part of a Phaser series. Click here to see the first post of the series.

To add an image in Phaser you first load it in the preload() function, assigning it a key. Then you place it on screen in create() with this.add.image(), using that key.

Why two steps? Images are files, and Phaser loads them over the network. preload() queues the files, and Phaser’s loader downloads them all before calling create(). By the time your create() code runs, the texture is ready to use.

You can add images as GameObjects:

function preload() {
  this.load.image('apple', 'apple.png')
}

function create() {
  this.add.image(200, 200, 'apple')
}

'apple' is an identifier we choose. 'apple.png' is the path of the image file, relative to the page running the game.

Note that 200, 200 is the position we’re going to put the image.

It refers to the center of the image.

Changing the origin

To make the position refer to the top left corner, which is easier to reason about, you can call the setOrigin() method on the image:

const image = this.add.image(200, 200, 'apple')
image.setOrigin(0, 0)

The default origin is (0.5, 0.5), the center of the image. (0, 0) is the top left corner, (1, 1) the bottom right.

Scaling and flipping

Once an image has been created and added, we can perform several operations on it, including scaling it:

image.setScale(2)

2 doubles the size, 0.5 halves it. You can also pass two values to scale each axis independently:

image.setScale(2, 1) //twice as wide, same height

You can flip it:

image.flipY = true
image.flipX = true

And you can move it after creation by changing its coordinates:

image.x = 400
image.y = 100

When the image doesn’t show up

If you see a small placeholder texture instead of your image, check two things.

First, the key. The string you pass to this.add.image() must match the one you used in this.load.image() exactly. A typo like 'appel' gives you the placeholder, not an error.

Second, where you load the file. Calling this.load.image() inside create() doesn’t work, because the loader only runs automatically as part of preload(). Keep all your load calls there.

Tagged: Phaser · All topics
~~~

Related posts about phaser: