Adding a Speed Power-Up to a Phaser3 Game

Here’s how to make a power-up that increases the speed for five seconds.

Step by Step

Create a power-up image and put it into your game directory (preferably assets/).

Load the image in the preload() method.

  this.add.image('sboost', 'assets/speedboost.png')

It’s probably a good idea to make the power-up part of a group even if we’ll have one for now.

Someplace in your create() method add a group and a function to make one of the group.

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

  let const createSpeedBoost  = (x,y) => {
    let sb = powerups.create( x, y, 'sboost')
    sb.setScale(2)
    // more stuff, maybe play a sound
  }

  createSpeedBoost()

Now it’s just a matter of knowing when you want to place the power-up and where. For example, let’s randomly place a power-up every 10 seconds at a random position on the board.

Add the following within the create() method:

  let puIterval = setInterval( () => {createSpeedBoost(rX(), rY())}, 10000)

We can actually simplify this by putting the rX() and rY() into the function itself.

[Creating Random X and Y Functions in Phaser3]

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

  let const createSpeedBoost  = (x,y) => {
    let pu = powerups.create( x || rX(), y || rY(), 'pu//)
    pu.setScale(2)
  }

  let puIterval = setInterval(createSpeedBoost, 10000)

Now to have the power-up actually do something. We could do this with a collider, but let’s use overlay instead. For this power-up I’m just increasing speed.

Add the following near your other colliders in your create() method.

  this.physics.add.overlay(pl, powerups, speedboost)

Now for applying the speed.

It’s a common error to just increase the speed of player rather than the overall speed when a key is down. This gives a sudden bump in speed, but as soon as you hit a wall or something the speed goes away.

To do this we need to add the value for the current speed to the player itself. Find where your main player object is created and add the following to keep track of speed values:

  pl.curSpeed = 400

Now we need to change the update() method to use these instead:

  } else if (k.RIGHT.isDown) {
    pl.setVelocityX(pl.curSpeed)
  } else if (k.LEFT.isDown) {
    pl.setVelocityX(-pl.curSpeed)
  }

Now we just need to change the pl.curSpeed when the player hits the power-up.

const speedboost = (p,u) => {
  u.destroy()
  p.curSpeed += 500
  setTimeout( () => {p.curSpeed -= 500}, 5000)
}