DEV Community

Cover image for Getting Started with Phaser 3 pt. II
Connor Schratz
Connor Schratz

Posted on

Getting Started with Phaser 3 pt. II

Alt Text

Introduction

Last week I discussed the basics of setting up a Phaser 3 game with a Node.js and Express. Now that we have an understanding of how to get the game instance up and running on our server, let's take a look at how we can add images, sprites, audio, and other visuals to our game instance. This is where the real fun of Phaser 3 starts to shine! Phaser implements different views for the game and calls them scenes. We'll create 2 different scenes in this tutorial and load different assets for each scene. To start off we're going to handle the title scene.

Modifying the Game.js file

In order to add additional scenes into our Phaser game we'll need to make a few modification in the Game.js file. Here's what changed.

import PlayScene from './scenes/playScenes.js';
import TitleScene from './scenes/TitleScene.js';

const config = {
  width: 800,
  height: 600,
  type: Phaser.AUTO,
  audio: {
    disableWebAudio: true
  },
  physics: {
    default: 'arcade',
    arcade: {
      fps: 60,
      gravity: {y : 0},
    }
  },
};

const game = new Phaser.Game(config);

game.scene.add('PlayScene', PlayScene);
game.scene.add('TitleScene', PreloadScene);
Enter fullscreen mode Exit fullscreen mode

As you can see in the final 3 lines, we setup the game to have additional scenes and we're importing those scenes at the start of the file. So we'll go ahead and make three new Javascript files in a scenes folder within the public directory.

TitleScene.js

First let's go ahead an add a background image into our game scene on Phaser 3. In order to add a background we'll have to set up an assets folder within our public directory. Here's the image we'll use for the background:

Alt Text

Now that the image is added to the assets folder we can load it as a background image within the game. Let's take a look at the code responsible for doing that.

import Phaser from 'phaser';
import background from '../assets/img/Space.jpg';

class TitleScene extends Phaser.Scene {
  constructor() {
    super('TitleScene');
  }

  preload() {
    this.load.image('background', background);
  }

  create() {
    this.add.image(0, 0, 'background').setOrigin(0, 0).setScale(0.6);
  }

export default TitleScene;

Enter fullscreen mode Exit fullscreen mode

Breaking down this code block, we can see that within the preload function we're loading the image background that we put into the assets folder earlier. Now in the create function we're adding an image to the actual scene when it is rendered. Below you'll see what it looks like.

Alt Text

Now that we have a basic background, let's add a way for our game to advance to the next scene. We can do this by adding a bit of text to the screen and making the text interactive. Add this line into the TitleScene.js file that we created above.

this.add.text(280, 350, `Your Game Name`, {
  fontSize: '32px',
  fill: '#FF0000',
  fontStyle: 'bold',
}); 
this.add.text(225, 400, `Click Here To Play!`, {
  fontSize: '32px',
  fill: '#FF0000',
  fontStyle: 'bold',
}).setInteractive( {useHandCursor: true}).on('pointerdown', () => this.scene.start('PlayScene'));
Enter fullscreen mode Exit fullscreen mode

Now whenever a user clicks on that text block the scene will change to the PlayScene that we'll create later.

Alt Text

Looking pretty good so far, now for on last touch, we're going to add in some music for our game, because what fun is a game without a great soundtrack? In order to do this we'll have to modify the preload and create functions. I'll break down each one below.

preload()
this.load.image('speaker', './assets/img/speaker.png');
this.load.audio('loading', './assets/sounds/Ballistics.mp3');
Enter fullscreen mode Exit fullscreen mode
create()
this.add.image(780, 580, 'speaker').setScale(.1).setInteractive({useHandCursor: true}).on('pointerdown', () => music.play());

const music = this.sound.add('loading', {
    mute: false,
    volume: 0.15,
    rate: 1,
    detune: 0,
    seek: 0,
    loop: true,
    delay: 0,
  });
Enter fullscreen mode Exit fullscreen mode

The only thing we're not familiar with in these two code blocks is the music instance that is being created. In order to add music you must specify what audio file you want to play, here we're doing that by referencing the 'loading' audio that we included in the preload function, the object following that is where you can specify the settings of the audio, since we just want this to be our background music we're setting the loop property to true. Great! We've made the first scene of the game, I'll include a full snapshot of the code just in case anybody missed a line. Now onto the PlayScene!

class TitleScene extends Phaser.Scene {
  constructor() {
    super('TitleScene');
  }

  preload() {
    this.load.image('background', './assets/img/Space.jpg')
    this.load.image('speaker', './assets/img/speaker.png')
    this.load.audio('loading', './assets/sounds/Ballistics.mp3')
  }

  create() {
    this.cursors = this.input.keyboard.createCursorKeys();
    this.add.image(0, 0, 'background').setOrigin(0, 0).setScale(0.6);
    this.add.image(780, 580, 'speaker').setScale(.1).setInteractive({useHandCursor: true}).on('pointerdown', () => music.play());
    this.add.text(280, 350, `Your Game Name`, {
      fontSize: '32px',
      fill: '#FF0000',
      fontStyle: 'bold',
    });
    this.add.text(225, 400, `Click Here To Play!`, {
      fontSize: '32px',
      fill: '#FF0000',
      fontStyle: 'bold',
    }).setInteractive( {useHandCursor: true}).on('pointerdown', () => this.scene.start('PlayScene'));

    const music = this.sound.add('loading', {
      mute: false,
      volume: 0.15,
      rate: 1,
      detune: 0,
      seek: 0,
      loop: true,
      delay: 0,
    })
  }
}

export default TitleScene
Enter fullscreen mode Exit fullscreen mode

PlayScene.js

For the sake of brevity, I'm just going to include the setup of the PlayScene with the sprites for the game. Next week, we'll cover making the game interactive, so don't worry! Let's take a look at the basic setup for the PlayScene below.

export default class PlayScene extends Phaser.Scene {
  constructor() {
    super('PlayScene');
  }

  preload() {
    this.load.image('background', './assets/img/background.png');
    this.load.image('ship', './assets/img/spaceship.png');
    this.load.image('asteroid', './assets/img/asteroid.png');
  }

  create() {
    this.add.image(0, 0, 'background').setOrigin(0, 0).setScale(0.6);
    this.add.image(0, 400, 'background').setOrigin(0, 0).setScale(0.6);

    this.ship = this.physics.add.image(400, 300, 'ship').setScale(0.1);

    this.asteroid = this.physics.add.image(225, 550, 'asteroid').setScale(0.03);
    this.asteroid1 = this.physics.add.image(225, 250, 'asteroid').setScale(0.03);
    this.asteroid2 = this.physics.add.image(525, 250, 'asteroid').setScale(0.03);
 }
  update() {

  }
}
Enter fullscreen mode Exit fullscreen mode

So let's breakdown this code a bit, but most of it we should already be familiar with. In the preload we're loading in 3 images for our scene, the background we used for the TitleScene, a ship, and an asteroid. In the create funciton we're adding each of these images to the scene. In order to just get the star background in the scene, we'll load the background image twice in two separate locations (once at 0 on the y-axis and once at 400). From there we're creating the image for the ship we'll use. Now this is where it differs from before. Since eventually this ship will move around the screen we're adding the image as part of the physics engine of Phaser 3. It's just the same as before, but now in the next tutorial we'll be able to apply physics to the ship to get it moving around. Finally we're adding in 3 asteroids to the screen, all of which will be part of the physics engine of Phaser 3 as well. If done correctly, you should be looking at screen like this!

Alt Text

Conclusion

Just to wrap it all up, we've covered how to include images, audio, and additional scenes into our game. It's really easy to get creative and use whatever sprites or backgrounds you want in your game. Next week we'll take a look at adding movement to the sprites we've imported so far so that we can get this game up and running! See you all next week!

Discussion (0)