Picking Up Coins in a Phaser3 Game

Here’s how to add coins — or anything really — that you can pick up to increase your score.

Step by Step

Create an image of the thing you want to pickup.

Add it to your assets/img in your game directory.

Find a sound to play when you pickup the coin.

💎 Adding Sound to Your Phaser3 Game

Download the sound and put it into your assets/snd directory. You might want to rename it to something friendlier to include in your code, but never remove the suffix.

Load the image and the sound in your preload() method.

    this.load.image('coin', 'assets/img/coin.png')
    this.load.audio('coinsnd', 'assets/img/coinsnd.wav')

Now we need to create the actual game objects that use the assets. We’ll use a group for the coins.

Add the following to the create() method:

    let coins = this.physics.add.group()

Let’s go ahead and create a procedure function to make an individual coin and place it on the map. This is a pretty standard thing to do.

Add the following to your create() method:

    let coins = this.physics.add.group()

    const createCoin = (x,y) => {
      let c = coins.add(x, y, 'coin')

    createCoin(300,300) // just a test

At this point if you want to allow a coin to be created randomly anywhere on the board you change your code to use rX() and rY().

      let c = coins.add(x || rX(), y || rY(), 'coin')

[Creating Random X and Y Functions in Phaser3]

Now you have a choice to make. Do you want your coins to be something you can jump off of, or do you want them to simply disappear when you contact them? For the first, use a collider and the second use overlap. We’ll use the second.

Add something like the following to your create() method. The pl is your global for the player.

    this.physics.add.overlap(pl, coins, getCoin)

Now we need to write the getCoin function someplace above the overlap.

    const getCoin = (p, c) => {

We destroy the coin instance and then make another one.

So now we should be able to collide with the coin and have it disappear and make another one.

Let’s add the sound.

Back up at the top of create() let’s create the sound object.

    let coinsnd = this.sound.add('coinsnd')

Returning back to our getCoin we can now play the sound.

    const getCoin = (p, c) => {

[Adding Sound to Your Phaser3 Game]