Adding mask layer in Phaser 3 | HTML5 Game Development
In Phaser 3, mask layers empower you to control which parts of your game are visible. This technique unlocks a variety of visual effects, from creating spotlights and vignettes to revealing hidden areas and implementing fog of war mechanics.
Understanding Masks in Phaser 3
- A mask layer is a black image or a Phaser Graphics (Phaser.GameObjects.Graphics) object that defines the visibility of other game objects.
- Black pixels in the mask allow objects to be seen clearly, while transparent pixels completely hide them.
Example of Mask:
Creating and Applying Masks:
Here’s a step-by-step guide on incorporating masks into your Phaser 3 project:
1. Setup the Phaser 3 Game (optional):
If you have not already setup the game then you can clone this repo. This is Phaser 3 and Vite JS Bolierplate for making website games. Link is here:
2. Create your scene:
Create your game scene, add the all game objects in a Container
then we will apply mask on that container in Create
function.
this.gameSizeX = 1 * this.game.config.width;
this.gameSizeY = 1 * this.game.config.height;
let bgContainer = this.add.container(0, 0);
for (let row = 0; row < this.gameSizeY / 60; row++) {
for (let col = 0; col < this.gameSizeX / 60; col++) {
let grassBg = this.add.image(col * 60, row * 60, "grass-bg").setOrigin(0, 0);
bgContainer.add(grassBg);
}
}
for (let i = 0; i < Phaser.Math.Between(100, 150); i++) {
let grass = this.add.image(Phaser.Math.Between(0, this.gameSizeX), Phaser.Math.Between(0, this.gameSizeY), "grass").setOrigin(0, 0);
bgContainer.add(grass);
}
for (let i = 0; i < Phaser.Math.Between(50, 100); i++) {
let brush = this.add.image(Phaser.Math.Between(0, this.gameSizeX), Phaser.Math.Between(0, this.gameSizeY), "brush").setOrigin(0, 0)
bgContainer.add(brush);
}
for (let i = 0; i < Phaser.Math.Between(40, 50); i++) {
let tree = this.add.image(Phaser.Math.Between(0, this.gameSizeX), Phaser.Math.Between(0, this.gameSizeY), "tree").setOrigin(0, 0)
bgContainer.add(tree);
}
3. Adding Mask:
After loading all game objects, add your mask image into scene then convert into mask.
let maskImg = this.make.image({ x: 0, y: 0, key: "mask", add: false }).setOrigin(0, 0).setDisplaySize(this.gameSizeX, this.gameSizeY);
var mask = maskImg.createBitmapMask();
bgContainer.mask = mask;
Now, you will see the corners of the container hidden due to mask layer. This is real use of the mask layer in my game. You can use it for your mask layers. Also you can check more examples on the phaser website.
START LEARNING PHASER 3 TODAY:
Conclusion
By mastering mask layers in Phaser 3, you gain a powerful tool to enhance your game’s visuals and create captivating effects. With a little creativity and experimentation, you can unlock a world of possibilities for masking in your HTML5 game development endeavors. Happy Coding!!!