Multi-platform Games with PhaserJS

By Ali Cormack

No one wants to write the same code for different platforms. It's a waste of resources, time, and effort. Luckily game developers have caught on, and designed engines such as Unity, Unreal, and CryEngine with this in mind. Make your assets, write the code, and publish to every platform under the sun, from consoles to mobiles. 

However these are heavy duty solutions. Not every project needs all the 3D features these provide, and the learning curve is steep for what may be a relatively simple game. This is where Phaser comes in. 

In this blog I'm going to go over some of the best features of phaser, and show how you can combine it with ios development for silky smooth native feeling games.

What is PhaserJS?

PhaserJS Game

PhaserJS is an open source HTML5 game development JavaScript and TypeScript framework built upon the tried and tested Pixi.js renderer. This means it works fantastically on both desktops and mobiles (though we have found that older devices do occasionally struggle), so you can make it once, and publish. It also offers a variety of canvas scaling options so you can adapt your game for any screen size.

It also includes a fully fledged physics engine, and animation capabilities, so you should be able to focus on designing rather than wrestling with getting the engine to where you want it. This is ideal for someone who wants to move away from dated software such as Flash, and into new realms of capability. If you've done 2D development previously, you should be right at home with Phaser. 

Some of the features include:

  • Tilemaps
  • Sprites
  • Particle Engine
  • Preloader
  • Camera
  • Device Scaling
  • Sound
  • Multitouch Input
  • Gamepad Input

You can also combine it with any of your favourite javascript libraries (such as gryo.js for accelerometer input) to get exactly the toolset you need.

Installing & getting started

PhaserJS Game Screenshot

Phaser is an extremely lightweight framework (only 618kb in it's minified form), you simply need to include the javascript file and you're good to go. You can grab Phaser (v2.0.3) from their github.

Once you've grabbed the files, just drag and drop phaser.js from the build folder into your project. I'm placing all the files in the root for this tutorial, but you'll want a better structure once you start creating full blown games (and using WebStorm as my editor, but any will do).

You'll also need a js file for your game. Create a file called 'gametest.js' in your root js directory and setup index.html to reference it like so:

<title>Phaser Test Game</title>
        <!-- Phaser -->
        <script src="phaser.js"></script>
        <!-- Main Game File -->
        <script src="gametest.js"></script>

 First Phaser game

As with any javascript framework you can code in a multitude of ways, however phaser allows to use a good tool in the form of GameStates. These can be swapped out and transitioned between when moving through menu -> game -> pause -> gameover etc. These can also include methods for preloading assets, creating them, and updating for each state. The following addition to gametest.js simply sets up a state, and sets it to be the default for our demo.

var GameState = function(game){};

GameState.prototype.preload = function() {
//Here you can preload images, audio, spritesheets and so on.

GameState.prototype.create = function() {
//This is called immediately after preloading.

GameState.prototype.update = function() {
//This method is called every frame.

//This line instantiates a new Phaser Game with a resolution of 1136x640 (iPhone5 Res), names it 'game', 
//and adds GameState as the default state.
var game = new Phaser.Game(1136, 640, Phaser.AUTO, 'game');
game.state.add('game', GameState, true);


Now we need some content! We're going to make a simple fly and avoid demo to demonstrate how one piece of code can work across multiple platforms (in this case focusing on ios). Apologies in advance for the programmer art. You can grab all the assets used in this zip.

We'll now add the player using a prototype constructor. Creating a prototype allows us to extend a class by adding custom properties to it, which is deal for objects such as enemies and players. I also enabled the player to utilise phasers physics engine, meaning it can now have velocity and interact with other elements. I'll be commenting the code throughout to give more indepth explanations, but please leave a comment if anything needs clarifying.

var GameState = function(game){};

var stageSize = {width:1136, height:640};
var centerPoint = {x:stageSize.width/2, y:stageSize.height/2};

GameState.prototype.preload = function() {
 //We're preloading all the assets for the game to avoid any potential load-lag later.'player', 'plane.png');

GameState.prototype.create = function() {
    //This is called immediately after preloading. = 0x4488cc;

    //Here we add an Player object to the stage. This is constructed using a prototype as defined below.
        this.player = new Player(, 150, centerPoint.y,

    //Just for good measure, i've added an fps timer. = true;
    this.fpsText =
        20, 20, '', { font: '16px Arial', fill: '#ffffff' }

GameState.prototype.update = function() {
    //This method is called every frame.
    //We're not doing anything but updating the fps here.
    if ( !== 0) {
        this.fpsText.setText( + ' FPS');

var Player = function(game, x, y, target){
    //Here's where we create our player sprite., game, x, y, 'player');
    //We set the game input as the target = target;
    //The anchor is the 'center point' of the sprite. 0.5, 0.5 means it will be aligned and rotated by its center point.
    this.anchor.setTo(0.5, 0.5);
    //Finally we enable physics so we can move the player around (this is how easy physics is in Phaser), Phaser.Physics.ARCADE);
    //We need a target position for our player to head to
    this.targetPos = {x:this.x, y:this.y};
    //And an easing constant to smooth the movement
    this.easer = .5;
    //Health = 100;

//We give our player a type of Phaser.Sprite and assign it's constructor method.
Player.prototype = Object.create(Phaser.Sprite.prototype);
Player.prototype.constructor = Player;

var game = new Phaser.Game(stageSize.width, stageSize.height, Phaser.AUTO, 'game');
game.state.add('game', GameState, true);

Now we need to make the plane fly around. I'll be making it move to the latest tapped/clicked position. To do this we just define the Player's update method like so:

Player.prototype.update = function(){

    //If the target's (which we have assigned as active pointer is down
    if ({
        //Make our new target position the pointers position
        this.targetPos = {,};

    //Now work out the velocities by working out the difference between the target and the current position, and use an easer to smooth it.
    var velX = (this.targetPos.x-this.x)/this.easer;
    var velY = (this.targetPos.y-this.y)/this.easer;

    //Set the Players physics body's velocity
    this.body.velocity.setTo(velX, velY);


You'll also need to add the following to your Player's contruction method.

//We need a target position for our player to head to
this.targetPos = {x:this.x, y:this.y};
//And an easing constant to smooth the movement
this.easer = .5;

Test your game and your pilot should now fly to where you click! You can also hold the mouse down for constant movement. 

60fps PhaserJS Game

Now we need some bad guys to avoid, which in this case is blimps. We'll have them come in from the right of the screen. You could obviously expand on this concept however you want, by making the plane able to shoot down blimps, and so on. Firstly, much like the Player, we'll create a Blimp prototype.

var Blimp = function(game, player){

    //Give the blimp an x offscreen, a random y, and a speed between -150 and -250
    var x = stageSize.width+200;
    var y = Math.random()*stageSize.height;
    this.speed = -250-Math.random()*150;
    this.player = player;

    //Create a sprite with the blimp graphic, game, x, y, 'blimp');

    //Again, enable physics and set velocity, Phaser.Physics.ARCADE);
    this.body.velocity.setTo(this.speed, 0);

    //Set a scale between 1 and 1.5 for some random sizes
    this.anchor.setTo(0.5, 0.5);

    //This handy event lets us check if the blimp is completely off screen. If it is, we call blimpOutOfBounds, and get rid of it.
    this.checkWorldBounds = true;, this);

    //Whether the blimp has been hit by the player yet.
    this.hit = false;

function blimpOutOfBounds(blimp){

Blimp.prototype = Object.create(Phaser.Sprite.prototype);
Blimp.prototype.constructor = Blimp;

The blimps are now good to go, but nothing will happen if you republish. We need to make them spawn at intervals. Phaser comes with a Timer class that is perfect for just this. Place this code in your GameState create function. It simply adds a looping timer that fires every 2.5 seconds, creating a new Blimp.

this.blimpGroup =;
this.blimpTimer =*2.5, function(){
    var blimp =
        new Blimp(this, this.player)
}, this);


You should now see blimps flying at you! However being invincible isn't a particularily fun game mechanic. We'll need to check when the player is in contact with a blimp. Add this function after the previous code:

Blimp.prototype.update = function(){

    //As a simple form of hit detection (Phaser also supports pixel perfect HD, but i'll keep it simple) we'll detect the bounds and see if they intersect.
    var boundsA = this.player.getBounds();
    var boundsB = this.getBounds();

    //If the bounds intersect and it's not already hit.
    if(Phaser.Rectangle.intersects(boundsA, boundsB) && !this.hit){
        this.hit = true;

        //Detract 20 from the players health and set the alpha to represent it. -= 20;
        this.player.alpha =;

        //Change the velocity to a downwards fall
        this.body.velocity.setTo(this.body.velocity.x/2, 100);

        //Phaser also lets you use Tweens to easily smooth movement. Here i've smoothly rotated downwards to give the impression of falling.
        .to({rotation: -Math.PI/8}, 300, Phaser.Easing.Linear.In)

So the player can be hurt now. But what about if they get below 0 health? We need a gameover screen. This is easy as pie. Just add the following to your GameState update function:

if( <= 0){
    //We pass in the player, blimpgroup, and blimptimer in order to remove them
    gameOver(this.player, this.blimpGroup, this.blimpTimer);

As well as this to the bottom of your code:

function gameOver(player, blimpGroup, blimpTimer){

    //Destroy the group of blimps
    //Kill the player
    //Remove the timer;

    //Create some GAME OVER text using a text style. Set the anchor to 0.5, 0.5 so it's perfectly centered.
    var textStyle = {font:"28px Arial", fill: "#FFFFFF", align:"center"};
    game.add.text(,, 'GAME OVER MAN. GAME OVER.\nCLICK TO PLAY AGAIN', textStyle)
    .anchor.setTo(0.5, 0.5);

    //We want the player to be able to restart, so add an click event.
    game.input.onDown.addOnce(newGame, this);


function newGame(){
    //This sets the state of your game to a fresh version of GameState, starting it all over again.
    game.state.add('game', GameState, true);

And there you have it! Now once you've hit 5 blimps, it's game over, and you can go again. If you're having any problems download the source files and take a look. 

The main advantage Phaser gives you is a strong toolset to get started making games right away. As you can see from this example, most things you need are provided, you just need to supplement them with your own additions to get the result you desire. Most simple games rely on basic object creating, updating and destroying, which is incredibly easy with Phaser.

You can give it a go here.

Now lets see how it works on iPhone!

iPhone Development with PhaserJS

There are a couple of ways you can develop with Phaser on mobile devices, the first route that might come to mind is using tech such as PhoneGap or cordova, which would fit in perfectly with the HTML/JS side of web game development. I'm not going to over that here, but if you take a look through the following tutorials from us at Eden, you should see it's definitely a viable option:

For now we're going to keep it super simple and use native objective-c. Start by setting up a single view template xcode project, and changing the settings so it can only be landscape. 

Now add a UIWebView to your storyboard and hook it up to the provided UIViewController. Like so:

UIWebView with PhaserJS

There's only a minute amount of code you'll need, so just copy and paste this method into your view controller:

- (void)viewDidLayoutSubviews{
    [super viewDidLayoutSubviews];
    NSString *htmlFile = [[NSBundle mainBundle] pathForResource:@"index" ofType:@"html"];
    NSURLRequest *request = [[NSURLRequest alloc] initWithURL: [NSURL URLWithString:htmlFile] 
                                                  cachePolicy: NSURLRequestUseProtocolCachePolicy timeoutInterval:5];
    [self.webView loadRequest: request];

 We'll also need a css file to move the game into the very top left of the canvas. Create index.css, and add the following to it:

html, body {
    margin: 0;
    padding: 0;
    transform: transale3d(0,0,0);

Now import it into our index.html:


<title>Phaser Game Test</title>

        <script src="js/phaser.js"></script>
        <!-- Main Game Files -->
        <script src="js/gametest.js"></script>

Finally, we need to set the game to scale to our screen. For that just add these 3 lines to your GameState preload function in gametest.js: = Phaser.ScaleManager.EXACT_FIT;;;

Now all that's left is to add the game files to xcode. Organise the files like so in Finder first:

With images in assets, and the other filetypes in their respective folders. Just select all of these and drag them into your xcode project (Make sure to select "Create folder references for any added folders" when importing.):

Now test your game, and you should see our plane game from earlier! Just tap to move around. Easy peasy!


Phaser already has a strong community and a number of big name companies using it, and with bi-monthly updates it is constantly becoming stronger. If you're interested and want to learn more, i would highly reccomend a read over of the following:

  • Game Mechanics Explorer - An excellent resource which gives examples of the basic fundamentals of 2D game design with Phaser. Really, really useful for getting started, especially if you've moved from other dev platforms.
  • Phaser Examples - The official phaser examples page, for 80% of things, if you have a question, you can probably find a solution here.
  • Phaser Documentation - A very useful (although somewhat hard to navigate) set of docs for the framework. 
  • Phaser Forums - A growing community of Phaser enthusiasts. Make sure to browse before posting.
  • How to Learn the Phaser HTML5 Game Engine - A very handy guide on some of the finer details of Phaser.
  • Your first Phaser Game - The official intro tutorial by Phaser creator, Rich.

If you think you've got the hang of Phaser, why not try incorporating AngularJS, Ionic, and PhoneGap from the previous blog, and create an entirely HTML based game for every mobile platform under the sun. The world is your oyster!

We'll be releasing some very interesting stuff with PhaserJS here at Eden soon, so keep your eyes peeled!




comments powered by Disqus

We’re a top UK digital agency - wahoo!

By Sophie Hardbattle

We're Eden Agency - one of the UK's top digital agencies.

Read more

An Introduction to Building a SpriteKit-UIKit Hybrid App

By Alan Chung

A guide to help you get started on making an iOS app that seamlessly combines the visual punch of SpriteKit with the practicality of UIKit.

Read more

How to build a material design prototype using Sketch and Pixate - Part Three

By Mike Scamell

Part three of a three-part tutorial on building a material design prototype. This section focuses on adding more detail to the prototype in Pixate.

Read more

We're Hiring - Web Developer Role

By Craig Gilchrist

We are currently seeking a full time full-stack web developer to join the team at our Knaresborough office.

Read more

How to build a material design prototype using Sketch and Pixate - Part Two

By Mike Scamell

Part two of a three-part tutorial on building a material design prototype. This section focuses on creating a interactive login screen in Pixate.

Read more