jDataLab

3 minute read

This is the second part of [HTML5 Game Development with Phaser2]( {{site.url}}{{site.baseurl}}{% post_url 2018-07-03-phaser2 %} ). In the first part, we have set up a game container, import the Phaser library and create a new game object as well.

In this part, we will write three functions, preload, create and update, into the game container, which is the <script> block in Line 9.


1. The preload function: Loading game resources

Load an image with a name

game.load.image('dude', 'phaser-dude.png');
game.load.image('fish', 'fishie.png');
game.load.image('tiles', 'tiles-1.png');

Load a sprite sheet with a name

A sprite sheet is a number of image frames in a single image file. Using sprite sheets can not only speed up resource loading but also create animated characters.

game.load.spritesheet('player', 'dude.png', 32, 48, 9)

The first and second numbers specify width and height of each frame. The third number tells the total frames.

Load audio

game.load.audio('bgMusic', 'freestyle.mp3');

2. The create function: Adding sprites into the game

In the create function, we can add sprites and enable physics system.

Add an image and assign a name

var dude = game.add.sprite(0,0,'dude');
var fish = game.add.sprite(0, game.world.centerY, 'fish');

The first two numbers specify the x and y coordinates. The third string is the sprite name to be added.

Add a frame from a sprite sheet To add a single frame from a sprite sheet,

var player = game.add.sprite(0, 0, 'player');

By default, the first frame in the sheet is added. To select other frames in the sheet, e.g., the fifth frame,

player.index = 5;

Add a tile from a tile sprite Tilemaps are a very popular technique in 2D game to build the game world or level map from small tiles. The same as a spritesheet, tiles are grouped into a single file, referred to as tilesprites.

In Phaser2, we can load a tilesprite in the preload function:

game.load.image('tiles', 'assets/tiles-1.png');

Then display the entire tile map in the create function. The first two numbers specify the x and y coordinates.

tile1 = game.add.sprite(20, 30, 'tiles');

Also, we can select a piece of the map to display:

ground = game.add.tileSprite(0, game.world.height-68, 128, 64, 'tiles');

The first two numbers are the x and y coordinates. The third and fourth numbers are the dimensions to be displayed.

Add background music

The audio file should have been loaded tn the preload function. Assume the name of audio object is bgMusic,

In the create function, add the music and play it.

	var bgm = game.add.audio('bgMusic');
	bgm.loopFull()

Add text

To display a text and assign it a name for late update,

var scoreText = game.add.text(16, 16, 'score: 0', {fontSize: '32px', fill: '#fff', align: 'left'});
  • The first two numbers specify the x and y coordinates.
  • The third string gives the text to be displayed.
  • The fourth object in curly brackets specifies the text style.

Continue to Part 3