Adding images in Phaser 3 is a straightforward process, and involves 2 simple steps:
- Preload your Image
- Add your Image to a Scene
If you haven't yet got a game environment, I strongly suggest you read my article [Phaser 3 and Webpack in 2021]. Or if you're looking for a quicker solution, please feel free to download my Phaser 3 Game Boilerplate (free of charge!).
With that out of the way, let's get started.
1. Preload your Image
The first step is to preload your image. What this means is your code is loading the image into the device's memory. When something is loaded into the device's memory it becomes immediately available, and can be put into your game without any sort of lag or latency. This technique applies to images, but also other assets, such as audio and tilemaps.
My Phaser 3 Game Boilerplate comes with a file called BootScene.js. You can find it located in /src/scenes/BootScene.js.
Inside that file is a function called preload(). This is the function Phaser 3 uses to preload assets. We'll leverage it now.
To preload an image, simply add a this.load.image(), like so:
import {Scene} from 'phaser';
class BootScene extends Scene {
constructor() {
super("scene-boot");
}
preload() {
// Add this line:
this.load.image('cat-like', 'assets/cat-like-creature.png');
}
create() {
this.scene.start('scene-game');
}
}
export default BootScene;
The function this.load.image() takes two arguments: a key (which we will later use to reference our image, in this case 'cat-like'), and a path to the image file in question ('assets/cat-like-creature.png').
From there, we can move on to the next step...
2. Add your Image to a Scene
If you're working with my Phaser 3 Game Boilerplate, open up GameScene.js located in /src/scenes/GameScene.js. Otherwise, create a new scene to represent the scene in your game where you want to render your image. This could be a menu scene, or a level, etc.
In GameScene.js (or your custom scene), you'll want to next add a call to this.add.image(), similar to as follows:
import {Scene} from 'phaser';
class GameScene extends Scene {
constructor() {
super("scene-game");
}
create() {
const img = this.add.image(100, 200, 'cat-like');
}
}
export default GameScene;
What this does is creates a new variable named img, and assigns it to an image GameObject created by Phaser. The first two parameters of this.add.image() specify the x (100) and y (200) position. The third parameter is a string that refers to the image's key, which we set in the previous step (in this case 'cat-like').
And that's it! From there you can take your newly created img variable and do things with it.
Here's a quick list of fun things to try out:
img.setScale(0.5)orimg.setScale(2).img.setTint(0xFF0000)orimg.setTint(0x00FF00).img.setRotation(Math.PI).img.setFlipX(true).
If you found this tutorial helpful, please leave a comment below letting me know, and considering subscribing to this blog (you'll receive my Phaser 3 Game Boilerplate for free)!
Loading!