Build a Space Shooter with Phaser3 and JavaScript(Tutorial1)

Like many computer enthusiasts, I grew up playing video games on the classic Nintendo entertainment system. Some of my favorite games included Super Mario brothers, Legend of Zelda, Tetris, and Star Force. It’s been fun to share these game classics with my kids. They still find them fun. In this blog post series, I want to unpack building a 2D shooter game using Phaser3.js. Phaser3 provides a robust and fast game framework for early stage JavaScript developers.

From exploring the options in 2D game creation using Javascript, Phaser has grown an impressive community of game makers. Here are a few game samples that you would want to explore.

Space shooter assets from www.kenney.nl

In this post series, I wanted to collect a few resources, tools, and links to help you get started building a space shooter game with Phaser 3. We’ll be drawing from the inspiration of classic games like Space Invaders.

In terms of JavaScript writing style, we’re going to keep the code samples as simple as possible to express core concepts. If you need to get started with JavaScript, I recommend checking out the free sources at CodeAcademy to start exploring the language. We’ll be drawing inspiration from classic games like Galaga and Star Force. Even though I’m trying to unpack these ideas for early stage JavaScript coders, I also want to provide examples that leverage ES6 coding structures. The Phaser3 documentation does not focus on this style of code organization. In general, I want to explore programming concepts that provide nice encapsulation and readability. We also want to make sure we can extend these coding patterns well.

The game we’re building may feel similar to this work here:
http://users.aber.ac.uk/eds/CS252_games/mwg2/JSGame/

In this tutorial, we want to encourage you to setup your work environment with Visual Studio code. You can also inspect the tutorial code in the following glitch sample.

https://glitch.com/edit/#!/awg-tutorial?path=shooter.js:1:0

Setting up Visual Studio Code

In this series, I recommend setting up Visual Studio Code on your computer. It’s a robust tool for web development and works well for JavaScript projects. You can find instructions to install VS Code using this link. I also recommend using the Visual Studio Code Live server extension to make it easier to hot re-load your code changes. Please refer to the following video for details.

Downloading some boilerplate code

To save some time, I have organized a ZIP file with a collection of code and graphics that you can leverage in building your own shooter game. You’re encouraged to play and build with these assets, sounds, and code samples to elaborate on your own game. For this first exercise, we just want to get a ship displayed to the screen and move it around using arrow keys.

  • Download the boilerplate code from here.
  • Extract the ZIP file to a location on your computer. We’ll call this your working directory. For me, I might store my files in “c:\alienWarGame-tutorial1.”

Let’s explore the contents of this boilerplate code

  • shooter.js: This JavaScript file will contain our game objects and behavior code.
  • shooter.html: This HTML file provides a home for our JavaScript game code. (see the code below) Please note that we’re downloading phaser.js (version 3.11) from a content delivery network. In the body of the HTML file, we import our shooter.js. Remember to install “Live server” extension for Visual Studio. You will be able to right click on the code HTML file and select “open with Live server.” This will load the file on a small HTTP server on your computer. All phaser games need to be hosted on a web server.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
<!doctype html>
<html lang="en">
<head>
    <meta charset="UTF-8" />
    <title>Space Shooter Tutorial 1</title>
    <script src="//cdn.jsdelivr.net/npm/phaser@3.11.0/dist/phaser.js"></script>    
    <style type="text/css">
        body {
            margin: 0;
        }
    </style>
</head>
<body>
    <script src="shooter.js"></script>    
</body>
</html>

Breaking Down Shooter.js

All Phaser games start with a little bit of configuration. In this “config” object below, we establish a screen size of 800 pixels by 600 pixels. This will be our drawing surface for the game. To help detect if objects bump into each other, we will be leveraging the ‘arcade’ physics engine included in Phaser3.


1
2
3
4
5
6
7
8
9
10
var SCREEN_WIDTH = 800;
var SCREEN_HEIGHT = 600;
var config = {
    type: Phaser.AUTO,
    width: SCREEN_WIDTH,
    height: SCREEN_HEIGHT,
    physics: {
        default: 'arcade'
    }
};

Ok. Let’s build our Space ship player object. In Phaser 3, they have been working to improve the framework to leverage modern JavaScript features like Es6 classes. The class will help us store the properties of the ship. Properties will include stuff like the location of the ship on the screen, object state, and texture. The class will also include several methods for moving the ship around. In the constructor method, we accept a scene object and location on the screen. (x,y). The call to “super” and “setPosition” helps associate the sprite with the parent scene and location. We call “setTexture” using the parameter of ‘ship’ to associate the ship graphic with the sprite. Finally, we set some variables(deltaX, deltaY) to configure how much the ship will move when we press keys.


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
class Ship extends Phaser.GameObjects.Sprite  {

    constructor(scene, x , y) {
        super(scene, x, y);
        this.setTexture('ship');
        this.setPosition(x, y);
        this.deltaX = 5;
        this.deltaY = 5;
    }

    moveLeft() {
        if (this.x > 0) {
            this.x -= this.deltaX;
        }
    }

    moveRight() {
        if (this.x < SCREEN_WIDTH) {
            this.x += this.deltaX;
        }
    }

    moveUp() {
        if (this.y > 0) {
            this.y -= this.deltaY;
        }
    }

    moveDown() {

        if (this.y < SCREEN_HEIGHT) {
            this.y += this.deltaY;
        }
    }

    preUpdate(time, delta) {
        super.preUpdate(time, delta);
    }
}

In the following method called ‘moveLeft’, we implement the math to move the sprite to the left. Since we’re moving left, we subtract 5 pixels from the current x position. We only execute this code if x is greater than zero. Most of the other movement methods operate in a similar manner.


1
2
3
4
5
    moveLeft() {
        if (this.x > 0) {
            this.x -= this.deltaX;
        }
    }

Let’s make a scene!

In the following class, we have to establish a Phaser scene object. It has a few simple tasks. In the “preload” method, need we load the ship sprite graphic from our assets folder.


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
class Scene1 extends Phaser.Scene {

    constructor(config) {
        super(config);
    }

    preload() {
        this.load.image('ship', 'assets/SpaceShooterRedux/PNG/playerShip1_orange.png');
    }

    create() {
        this.cursors = this.input.keyboard.createCursorKeys();
        this.myShip = new Ship(this, 400, 500);
        this.add.existing(this.myShip);
    }

    update() {
        if (this.cursors.left.isDown) {
            this.myShip.moveLeft();
        }

        if (this.cursors.right.isDown) {
            this.myShip.moveRight();
        }

        if (this.cursors.up.isDown) {
            this.myShip.moveUp();
        }

        if (this.cursors.down.isDown) {
            this.myShip.moveDown();
        }

        if (this.cursors.space.isDown) {
            // shooting guns goes here
        }
    }
}

The create method has does additional setup for our scene. We establish a property called cursors that will be used for detecting keyboard input like the arrow keys. We also create a ship instance at (400,500) and add it to the scene.


1
2
3
4
5
    create() {
        this.cursors = this.input.keyboard.createCursorKeys();
        this.myShip = new Ship(this, 400, 500);
        this.add.existing(this.myShip);
    }

We now can start moving the ship around using the update method. The if statements in update help us detect the various arrow keys. We call the appropriate method on the ship. In other words, if we press the LEFT button, we should call this.myShip.moveLeft().


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
    update() {
        if (this.cursors.left.isDown) {
            this.myShip.moveLeft();
        }

        if (this.cursors.right.isDown) {
            this.myShip.moveRight();
        }

        if (this.cursors.up.isDown) {
            this.myShip.moveUp();
        }

        if (this.cursors.down.isDown) {
            this.myShip.moveDown();
        }

        if (this.cursors.space.isDown) {
            // shooting guns goes here
        }
    }

Here’s the final step, we associate our game configuration information to a new game. We then add our scene.


1
2
var game = new Phaser.Game(config);
game.scene.add('scene1', Scene1, true, { x: 400, y: 300 });

If you’re really excited to learn more, I have found the learning from the examples very helpful.

Phaser Labs Examples

This entry was posted in technology. Bookmark the permalink.