Us­ing PhaserJS to Speed Up 2D Game De­vel­op­ment

This tu­to­rial will help you build a 2D plat­form ar­cade style game, us­ing the PhaserJS frame­work, within a few min­utes.

OpenSource For You - - Contents -

PhaserJS is a pop­u­lar, free and open source HTML5 frame­work for game de­vel­op­ment on mo­bile and desk­top browser plat­forms. It uses HTML5 Can­vas for ren­der­ing and also We­bGL if the de­vice or browser sup­ports it. It is one of the most pop­u­lar and easy-to-learn game de­vel­op­ment frame­works and is based on pure Web tech­nolo­gies such as HTML, CSS and JavaScript. With over 15,000 stars and al­most 5000 forks at the time of writ­ing this ar­ti­cle, it is also one of the most pop­u­lar and ac­tively main­tained game frame­works on GitHub.

Thou­sands of devel­op­ers all around the world use Phaser, as it has some great fea­tures which are listed below.

Sup­ports JavaScript and TypeScript: PhaserJS sup­ports both JavaScript and TypeScript; so either of these lan­guages can be used to de­velop games.

Uses We­bGL and Can­vas: PhaserJS uses both We­bGL and Can­vas in­ter­nally, and has the abil­ity to switch be­tween them based on browser sup­port. This al­lows fast and ro­bust ren­der­ing across var­i­ous mo­bile and desk­top plat­forms.

Op­ti­mised for mo­bile browsers: PhaserJS was built keep­ing the mo­bile Web browser as the tar­get plat­form, so it is highly op­ti­mised for mo­bile as well as for desk­top browsers.

Built-in physics en­gines: PhaserJS has three built-in physics en­gines — Ar­cade Physics, a light­weight en­gine use­ful for de­vel­op­ing ar­cade style games; Ninja Physics for ad­vanced tile sup­port; and p2.js, which sup­ports char­ac­ter rig­ging, con­straints and ad­vanced poly­gon sup­port.

As­sets preloader: As­sets, im­ages, sprites, sheets, sounds, tilemaps, JSON data, XML, etc, are loaded with ease, parsed and han­dled au­to­mat­i­cally—to be used in games and stored in the global cache.

Par­ti­cles, an­i­ma­tion and sprites: PhaserJS has a built-in par­ti­cle sys­tem, which al­lows devel­op­ers to eas­ily cre­ate cool par­ti­cle ef­fects such as rain, fire, snow and wa­ter. It sup­ports Flash CS6/CC JSON files to cre­ate an­i­ma­tion for sprites.

In­put sup­port: It sup­ports multi-touch, mouse and key­board. It also al­lows the user to code cus­tom ges­ture con­trol.

Plugin sys­tem: PhaserJS al­lows devel­op­ers to cre­ate their own plu­g­ins for their games and share them with the com­mu­nity.

Games cre­ated us­ing PhaserJS de­pend on and re­quire a mod­ern browser that sup­ports the Can­vas tag, which in­cludes Chrome, In­ter­net Ex­plorer 9+, Fire­fox, Sa­fari and Opera. It also works on mo­bile Web browsers such as stock An­droid 2.x browsers and later, and Mo­bile Sa­fari for iOS5 and later ver­sions.

Tip: The PhaserJS frame­work is open source and the source code of the frame­work is avail­able on GitHub. Devel­op­ers/pro­gram­mers are en­cour­aged to par­tic­i­pate and con­trib­ute to the project.

In­stalling the pre­req­ui­sites

Be­fore we start de­vel­op­ing our game us­ing PhaserJS, we need to in­stall Node.js, as the PhaserJS frame­work is also dis­trib­uted as an npm pack­age and this makes it easy to set up the project struc­tures to de­velop games.

In­stalling Node.js

Down­load and in­stall Node.js (https://nodejs.org/). PhaserJS is also dis­trib­uted as an npm pack­age, so we will use Node and npm to in­stall the PhaserJS frame­work.

In­stalling Phaser JS

We can in­stall PhaserJS as a node pack­age. Just run the fol­low­ing com­mand in the ter­mi­nal or at the com­mand prompt:

npm in­stall phaser This com­mand will in­stall the PhaserJS frame­work.

In­stalling an HTTP server

To run the PhaserJS project, we need to in­stall an HTTP server. Run the fol­low­ing com­mand in a ter­mi­nal or at the com­mand prompt:

npm in­stall -g http-server This will in­stall an HTTP server as a global mod­ule.

Test­ing if ev­ery­thing is in­stalled prop­erly

Cre­ate a folder for your project, and change di­rec­tory to it. Run the fol­low­ing com­mands at the com­mand prompt or in the ter­mi­nal:

mkdir my-game cd my-game

Ini­tialise the folder us­ing the fol­low­ing npm com­mand: npm init –y

This will cre­ate a pack­age.json man­i­fest file with vi­tal de­fault in­for­ma­tion about the project, and will add the nec­es­sary node mod­ules.

Now cre­ate an in­dex.html file and add the fol­low­ing code to it.

<!doctype html>

<head>

<ti­tle>My Game</ti­tle>

<script type=”text/javascript” src=”node_­mod­ules/phaser/ build/phaser.min.js”></script>

</head>

<body>

<div id=”hel­loWorld”></div> </body>

<script> var game = new Phaser.Game(640, 480, Phaser.AUTO, ‘hel­loWorld’, {

cre­ate: cre­ate

}); func­tion cre­ate() { var text = “OPEN SOURCE FOR YOU”; var style = { font: “45px “, fill: “#ff0000”, align: “cen­ter” }; var t = game.add.text(game.world.cen­terX, 240, text, style);

t.an­chor.set(0.5); } </script>

</html>

Fi­nally, start the server by run­ning the fol­low­ing com­mand at the com­mand prompt:

hs

The hs com­mand will start the HTTP server. Now, load http://lo­cal­host:8080 in your browser to run the project. If you see the out­put screen shown in Fig­ure 1, then you have suc­cess­fully in­stalled all the de­pen­den­cies re­quired.

Creat­ing a sim­ple 2D plat­form game

Now we are go­ing to cre­ate a sim­ple 2D plat­form game, that has a char­ac­ter who col­lects rings and scores points. The game con­sists of walls, on which the char­ac­ter can jump in or­der to col­lect the rings and score points. The player will use the ar­rows on the key­board to con­trol the char­ac­ter’s move­ments.

I have cre­ated some as­sets, like the back­ground im­age, game sprites, etc. You can down­load these from http://www. aniket.co/labs/phaser/as­sets.zip. We are go­ing to use these to de­velop this game. This zip file con­sists of four as­set files —

the sky, the player, the plat­form and the ring that will be used for our game.

Cre­ate a new folder that we can call ring-col­lec­tor. Move into that di­rec­tory.

mkdir ring-col­lec­tor cd ring-col­lec­tor

Ini­tialise the folder us­ing npm, and in­stall PhaserJS again for this folder as well. It will pull all the nec­es­sary node_ mod­ules. Run the fol­low­ing com­mands in a ter­mi­nal or at the com­mand prompt:

npm init -y npm in­stall phaser

Cre­ate a folder called as­sets and ex­tract the down­loaded as­sets.zip into it. Cre­ate an in­dex.html file, and add the fol­low­ing code into it:

<!doctype html>

<head>

<ti­tle>Ring Col­lec­tor</ti­tle>

<script type=”text/javascript” src=”node_­mod­ules/phaser/ build/phaser.min.js”></script>

</head>

<body>

<script type=”text/javascript” src=”game.js”> </script>

</body> </html>

In the in­dex.html file, load the PhaserJS frame­work and our game’s logic.

Now cre­ate a file called game.js in the same folder, and add the fol­low­ing code. I have also added com­ments for each line of code to ex­plain what it ac­tu­ally does and why we are us­ing it.

let game = new Phaser.Game(800, 600, Phaser.AUTO, ‘’, { preload: preload, cre­ate: cre­ate, up­date: up­date }); func­tion preload() {

//Load­ing as­sets such as back­ground im­age, ob­ject im­age, game sprites. game.load.im­age(‘sky’, ‘as­sets/sky.png’); game.load.im­age(‘ground’, ‘as­sets/plat­form.png’); game.load.im­age(‘ring’, ‘as­sets/ring.png’); game.load.im­age(‘player’, ‘as­sets/player.png’); }

// Vari­ables let player; let plat­forms; let cur­sors;

let rings; let points = 0; let pointsText;

func­tion cre­ate() {

// Since we are build­ing an ar­cade style game, we en­able ar­cade physics sys­tem us­ing fol­low­ing func­tion game.physics.startSys­tem(Phaser.Physics.AR­CADE);

// This func­tion will add ‘sky’ as­set as back­ground to our can­vas.

game.add.sprite(0, 0, ‘sky’);

// The plat­forms group con­tains the ground and the 3 ledges we can jump on

plat­forms = game.add.group();

// En­able physics for any ob­ject that is cre­ated in this group

plat­forms.en­ableBody = true;

// Here we cre­ate the ground. let ground = plat­forms.cre­ate(0, game.world.height - 64, ‘ground’);

// Scale it to fit the width of the game (the orig­i­nal sprite is 400x32 in size) ground.scale.setTo(2, 2);

// This stops it from fall­ing away when you jump on it ground.body.im­mov­able = true;

// Now let’s cre­ate three ledges, at 3 dif­fer­ent lo­ca­tions let ledge = plat­forms.cre­ate(400, 400, ‘ground’); ledge.body.im­mov­able = true; ledge = plat­forms.cre­ate(-150, 250, ‘ground’); ledge.body.im­mov­able = true;

ledge = plat­forms.cre­ate(400, 150, ‘ground’); ledge.body.im­mov­able = true;

// The player and its set­tings, such as height and width player = game.add.sprite(32, game.world.height - 150, ‘player’);

// En­able physics on the player game.physics.ar­cade.en­able(player);

// Player physics prop­er­ties, such as bounce and bound­ing it to can­vas only so it does not go off screen player.body.bounce.y = 0.2; player.body.grav­ity.y = 300; player.body.col­lideWorldBounds = true;

// Adding some rings to col­lect rings = game.add.group();

// We will also en­able physics for any ring that is cre­ated in this group

rings.en­ableBody = true;

// Here we’ll cre­ate 10 of them evenly spaced apart for (let i = 0; i < 10; i++)

{ // Cre­ate a ring in­side of the ‘rings’ group let ring = rings.cre­ate(i * 70, 0, ‘ring’);

// Add some grav­ity ring.body.grav­ity.y = 300;

// The pointsText dis­plays cur­rent score in top right cor­ner of can­vas

pointsText = game.add.text(624, 16, ‘Points: 0’, { fontSize: ‘32px’, fill: ‘#000’ });

// Us­ing key­board con­trols cur­sors = game.in­put.key­board.cre­ateCur­sorKeys(); func­tion up­date() {

// Col­lide the player and the rings with the plat­forms game.physics.ar­cade.col­lide(player, plat­forms); game.physics.ar­cade.col­lide(rings, plat­forms);

// Checks if the player over­laps with any of the rings, if he does call the col­lec­tRing func­tion

game.physics.ar­cade.over­lap(player, rings, col­lec­tRing, null, this);

// Re­set the play­ers ve­loc­ity (move­ment), if no key is pressed

player.body.ve­loc­ity.x = 0;

// If left or right key is pressed if (cur­sors.left.isDown)

{ // Move left player.body.ve­loc­ity.x = -150; } else if (cur­sors.right.isDown) { // Move right player.body.ve­loc­ity.x = 150; } else { // Dont move player.an­i­ma­tions.stop(); player.frame = 4;

// Al­lows the play­ers to jump only if they are touch­ing the ground. if (cur­sors.up.isDown && player.body.touch­ing.down)

{ player.body.ve­loc­ity.y = -350; func­tion col­lec­tRing (player, ring) {

// Re­moves the ring from the screen, when player touches the ring

ring.kill();

// Add and up­date the score points points = points + 10; pointsText.text = ‘Points: ‘ + points;

Here, on the first line, we have cre­ated an in­stance of a Phaser.Game ob­ject and as­signed it to the game vari­able.

The first two pa­ram­e­ters in the Phaser.Game func­tion are the width and height of the can­vas that Phaser cre­ates. The third pa­ram­e­ter can be Phaser.CAN­VAS, Phaser.WE­BGL or Phaser. AUTO, which are for ren­der­ing the set­ting you want to use for your game. I rec­om­mend that you use Phaser.AUTO, which will au­to­mat­i­cally try to use either We­bGL or Can­vas, based on which­ever the browser sup­ports. The fourth pa­ram­e­ter is an empty string. Here, you can give the ID of a DOM el­e­ment where you would like to add the can­vas el­e­ment on the page. We have left it blank, so by de­fault it will be ap­pended to the body el­e­ment. The last pa­ram­e­ter is an ob­ject that con­sists of three ref­er­ences to Phaser’s es­sen­tial func­tions.

The es­sen­tial func­tions are preload(), cre­ate() and up­date(). preload(): This is used to load the as­sets needed for our game. PhaserJS will au­to­mat­i­cally look for this func­tion when it starts, and load any as­set de­fined within it.

cre­ate(): This func­tion is used to cre­ate the game scene. Here, we add the as­sets loaded such as the back­ground im­age, plat­form, player/char­ac­ters and other game sprites.

up­date(): This func­tion is called by the core game loop in ev­ery frame. It helps to check what is hap­pen­ing in ev­ery frame, like if there is a col­li­sion be­tween the player and ob­ject, score up­dates, etc.

Fi­nally, you should end up with the fol­low­ing di­rec­tory struc­ture:

as­sets/ • plat­form.png

• player.png

• ring.png

• sky.png node_­mod­ules/

• phaser/ game.js in­dex.html pack­age.json

Now that we have added the code, let us start a server and see the fi­nal out­come. Run the fol­low­ing com­mand in the same di­rec­tory:

hs

The hs com­mand will start the HTTP server. Now, load http://lo­cal­host:8080 in your browser to run the project. If you see the out­put screen shown in Fig­ure 2, then you have suc­cess­fully cre­ated a sim­ple 2D plat­form ar­cade style game. You can use the ar­rows on the key­board to con­trol the char­ac­ter and col­lect rings.

I have up­loaded this sam­ple project to my GitHub repos­i­tory at https://github.com/aniketku­dale/ring-col­lec­tor. You can down­load it for ref­er­ence.

You will also find var­i­ous game physics ex­am­ples and tech­niques at https://phaser.io/ex­am­ples, which you can use in your game to make it more fun-filled.

Fig­ure 1: The my-game project run­ning in the browser

Fig­ure 2: The game we de­vel­oped is launched in the browser

Newspapers in English

Newspapers from India

© PressReader. All rights reserved.