Shooting bullets in Phaser 3 using Arcade Physics Groups

  • 3 Min. Read.

Phaser Physics Arcade Groups are one of the most powerful features of Phaser3, let’s take a look at how they work, by creating a small spaceship shooter example.

What we’ll cover

  • How to set up a Phaser 3 Arcade Physics Group
  • Create an Arcade physics group for pooling objects
  • Use the mouse to make the space ship move
  • Detect when lasers are out of bound and reset them
  • Object Pooling using Phaser Groups for improving performance
  • Phaser mouse and keyboard input events

Setup

Clone our repository and switch to the ‘start branch using git checkout start

Running a webserver

Because of the way Phaser loads assets, we need a webserver to make it work correctly. You can use PHP for this:

This will fire up a webserver in the current working directory. You can now navigate to http://localhost:9000 in your browser

Adding our ship

Open up main.js and let’s add our space ship in the create function:

Making the ship follow the mouse

To make the ship follow the mouse, we’ll make use of a pointermove event. Create a new function called addEvents with the following content:

This will make the ship follow the mouse on the horizontal axis.

Creating a laser group

We’ll create a class called LaserGroup which inherits from Phaser.Physics.Arcade.Group:

And next up create a new instance of LaserGroup in the create function (don’t forget to initialize the variable in the constructor):

Shooting a laser

In our function addEvents we’ll add a new listener to capture mouse clicks. This event is called pointerdown:

Afterwards create the function shootLaser:

And in our LaserGroup class we’ll add the function fireLaser:

And finally, we’ll add the fire method to the Laser:

Refresh your browser & try clicking, the laser beams should now shoot! … But after shooting for 30 times the bullets have run out, what gives?

Our pool with 30 Laser instances has depleted, since we never clean the lasers we shot. To do that, add the following code in the Laser class:

This will mark the laser as inactive, after it reached the end of the screen. Now we can infinitely shoot our bullets!

Adding keyboard events

To fire lasers with the spacebar / enter key, we can add 2 listeners:

To make sure our laser only shoots once, we can use Phaser.Input.Keyboard.JustDown(key). This function will only return true once until the key is pressed up again.

A concept by Wonderlus