How to add Collectibles to your Phaser 3.60 Game
Learn the steps to add collectibles like coins, stars, etc. to your Phaser 3.60 Game.
Hey there! Today, you will learn how to add various collectibles to your Phaser 3.60 game so that you can add various features to your video game related to such collectibles. Also, I have used Apple as an example of a collectible for this blog, you can use anything as a collectible for your game.
Note: Before following this blog, make sure that you have the sprite for the collectible item.
Firstly, you need to import the sprite and load it through the preload()
function on your main javascript file.
import apple from './assets/fruits/apple.png';
preload() {
this.load.image('apple', apple);
}
After that, add your collectible as a physics group in the create()
function. For that, you need to write the following code:
this.apple = this.physics.add.group({
key: 'apple',
repeat: -1,
setXY: { x: 350, y: 90 }
});
In the above code, the key
option specifies the key of the sprite of the collectible. And, the repeat
option specifies how many objects will be initially created in the group. You can change the number of the objects in the group after adding the physics group, too. Then, setXY
sets the initial position (x,y) for the collectible objects.
Then, you need to add collider to the apple physics group so that it does not fall off the screen.
this.physics.add.collider(this.apple, platforms);
After that, you will have to specify what happens when the player collides with the collectible by writing the code given below:
this.physics.add.overlap(this.player, this.apple, this.collectApple, null, this);
In my case, I have written this.collectApple
in the above code. This code will run the collectApple()
function that I have set up. You will have to change the function name to the function which you want to trigger when the player collides with the collectible.
Now, you can specify the position where you want to keep more collectibles by writing the given code:
this.apple.create(x, y, 'apple');
The above given code creates children of the apple physics group. You need to change the x
and y
fields to the coordinates of the position where you want to keep the other collectibles.
✨Voila! Your collectibles are ready to boost your game's mechanics! If you have faced any problems while following this tutorial, feel free to comment below. I will try my best to solve your problems.
Happy Coding! 🚀