Making Your First Phaser 3 Game in Modern Javascript - Part 3

Write better code using modern JavaScript for Phaser 3

by on 4 minute read updated on


Games can be one of the most complicated pieces of software you create. And the most fun.

It helps to use modern best practices to avoid messy bugs or more easily fix ones that come up.

Doing so saves you time and headaches. Most importantly it will help you make a better game.

In this article, we will show you how to create games in Phaser 3 using modern JavaScript and best practices.

We'll be creating the same game from the official Making your first Phaser 3 game guide. This way you can compare and contrast the differences.

In Part 2 we added platforms and created a player character. Go check it out if you haven't already.

Colliders

We have platforms and a player but they are not colliding with each other. Let's fix that by adding a collider for the player physics body and the platform static group.

 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
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
import Phaser from 'phaser'

const GROUND_KEY = 'ground'
const DUDE_KEY = 'dude'

export default class GameScene extends Phaser.Scene
{
	//...

	create()
	{
		this.add.image(400, 300, 'sky')
		
		const platforms = this.createPlatforms()
		this.player = this.createPlayer()

		this.physics.add.collider(this.player, platforms)
	}

	createPlatforms()
	{
		const platforms = this.physics.add.staticGroup()

		platforms.create(400, 568, GROUND_KEY).setScale(2).refreshBody()
	
		platforms.create(600, 400, GROUND_KEY)
		platforms.create(50, 250, GROUND_KEY)
		platforms.create(750, 220, GROUND_KEY)

		return platforms
	}

	createPlayer()
	{
		const player = this.physics.add.sprite(100, 450, DUDE_KEY)
		player.setBounce(0.2)
		player.setCollideWorldBounds(true)

		this.anims.create({
			key: 'left',
			frames: this.anims.generateFrameNumbers(DUDE_KEY, { start: 0, end: 3 }),
			frameRate: 10,
			repeat: -1
		})
		
		this.anims.create({
			key: 'turn',
			frames: [ { key: DUDE_KEY, frame: 4 } ],
			frameRate: 20
		})
		
		this.anims.create({
			key: 'right',
			frames: this.anims.generateFrameNumbers(DUDE_KEY, { start: 5, end: 8 }),
			frameRate: 10,
			repeat: -1
		})

		return player
	}
}

The collider is added on line 17 but we made more changes.

The createPlatforms() and createPlayer() methods now return the instance they are creating.

It is a best practice to return values for functions with names like create..., make..., construct..., etc. This makes for clearer and safer code as opposed to the function changing variables outside its scope.

Our createPlayer() method was previously changing this.player in the class scope. Now it creates a local variable and returns it without making unseen changes or side effects.

You generally want your functions to be as pure as possible. Some of the worst bugs are due to unintended mutations or side effects.

Keyboard Controls

Now that we've added a collider our player is interacting with the platforms as we expect.

Next, we will add some keyboard controls.

 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
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
import Phaser from 'phaser'

// constants...

export default class GameScene extends Phaser.Scene
{
	constructor()
	{
		super('game-scene')

		this.player = undefined
		this.cursors = undefined
	}

	// preload()...

	create()
	{
		this.add.image(400, 300, 'sky')
		
		const platforms = this.createPlatforms()
		this.player = this.createPlayer()

		this.physics.add.collider(this.player, platforms)

		this.cursors = this.input.keyboard.createCursorKeys()
	}

	update()
	{
		if (this.cursors.left.isDown)
		{
			this.player.setVelocityX(-160)

			this.player.anims.play('left', true)
		}
		else if (this.cursors.right.isDown)
		{
			this.player.setVelocityX(160)

			this.player.anims.play('right', true)
		}
		else
		{
			this.player.setVelocityX(0)

			this.player.anims.play('turn')
		}

		if (this.cursors.up.isDown && this.player.body.touching.down)
		{
			this.player.setVelocityY(-330)
		}
	}

	// ...
}

We added a cursors property on line 12 and then set it to Phaser's default cursor keys in the create() method on line 26.

The new update() method is where the input logic takes place. The code is the same as the official Phaser guide except we are using references to class properties (this.cursors and this.player) instead of globals.

Your browser window at http://localhost:8000 should automatically refresh. Then you can move your character with the left/right arrow keys and jump with the up key! 🎉

Coming Up

We've now transformed parts 6 and 7 from the official Making your first Phaser 3 game guide into modern JavaScript.

In the next part, we will add stars to collect and handle showing a score.

Let us know in the comments below if anything doesn’t work or is unclear. We’ll be happy to fix or clarify!

Be sure to sign up for our newsletter so you don't miss any future Phaser 3 game development tips and techniques!

Drop your email into the box below.

Learn to make an Infinite Jumper in Phaser 3 with modern JavaScript!

Drop your email into the box below to get this free 60+ page book and join our newsletter.

Learn more about the book here.

Phaser 3 JavaScript HTML5 Guide Tutorial

Want tips and techniques more suited for you?


You may also like...


Video Guides


Beginner Guides


Articles Recommended For You

Moving Platforms with Matter Physics in Phaser 3

by on

Are you working on a side-scrolling platformer in Phaser 3 using Matter Physics and having trouble with moving …

5 minute read

Scene Transition with Fade Out in Phaser 3

by on

Are you looking for a quick way to improve Scene transitions? A hard cut from one Scene to another is appropriate at …

6 minute read

Typewriter Effect for Text and BitmapText in Phaser 3

by on

Are you making a story-driven game like an RPG or interactive novel? Having text show up one character at a time is …

6 minute read

Firebase Leaderboard with Rex Plugins in Phaser 3

by on

Are you looking to add more replayability to your game? Leaderboards are a long-standing feature of single-player games …

9 minute read

Didn't find what you were looking for?


comments powered by Disqus