If you've read through the complete version of this course then you would've learned how to build a simple data driven application with Ionic by now. Typical business style applications are where HTML5 mobile frameworks like Ionic excel. They can't do everything though. If you want to build a game then you are going to have to use a different technology. Ionic does not provide functions that would be necessary for typical games, and the way in which the framework is designed and runs is just not suitable for those sorts of applications (Ionic certainly doesn't come with an in built physics engine, Phaser on the other hand has three!).

Fortunately, there are still options for games in the HTML5 mobile space. We're going to be looking at using the Phaser framework to build a simple mobile game. It's important to note that Phaser is not specifically a framework for mobile, many developers are creating browser based HTML5 games to run on the desktop.

Like Ionic though, since Phaser uses HTML5 technology then it can run on mobiles and be distributed through app stores just like native apps. When using HTML5 to build mobile games you do need to keep the performance limiations of mobile browsers in mind - HTML5 isn't a great option if you want to build 3D games with HD graphics and explosions, but if you want to build reasonably simple games (think Flappy Bird, Puzzle games, Platformers etc.) then HTML5 is a great choice.

Phaser is currently one of the most popular HTML5 game frameworks so I doubt you will regret the decision to pursue it, it is by far the most active framework on html5gamedevs.com and is being actively developed. Before we jump into building our first game, let's explore the environment a little and take a look at some examples that can be built with Phaser.

Pre-lesson Tasks

Getting Started with Phaser

Install XAMPP

Just like Ionic, Phaser needs to run on a webserver on your machine. Ionic has a nice little command built in to do that for you, but with Phaser you will need to set it up yourself. What you want is to be able to store all of your files locally and access them through the http protocol like this:

http://localhost/MyCoolGame

instead of through the file system like this:

file://Users/blah/blah/MyGame

because that doesn't work. I won't get into the technicalities behind why that doesn't work, but it has to do with the file:// protocol being much more restricted.

There are other methods to getting a webserver running on your machine, so feel free to do whatever you like, but a great option for both Mac and PC is XAMPP.

Download and Install XAMPP

Once you have XAMPP set up you should be able to access the XAMPP control panel:

XAMPP Control Panel

Open the XAMPP control panel and make sure the Apache Web Server is running

Now any files you store in your htdocs directory you will be able to access through localhost in the browser. On a Windows machine this will be located at:

c:\xampp\htdocs\

and on a Mac:

/Applications/XAMPP/htdocs

So if you store a file in htdocs/myfile.html you will be able to access it by going to http://localhost/myfile.html in the browser:

URL Bar

Download Phaser

Phaser is extremely easy to set up, it is literally just a single javascript file that you need to include. There's a few different ways to grab the source file, and you can even create a custom build that only includes the bits you need (which keeps the file size down), but for now we will just be downloading the full phaser.min.js file.

Go to the download page and download the min.js version of Phaser

We will go through setting this up to be used in an actual game in just a moment, but first let's talk a little bit about the game we will be building with Phaser.

Introducing: I Hate Squares

After completing the tasks above you should be ready to get started with Phaser, and you should at least be somewhat familiar with what Phaser is all about.

Now we need to figure out what we actually want to build. I wanted to avoid building something cliche like a Space Invaders or Snake clone and I also want it to be relatively simple. I like building simple, difficult and addictive games for mobile - they're reasonably quick to build, small enough for one developer to handle and can be very successful on the app stores - so in that fashion I came up with "I Hate Squares".

The premise is simple, you're a rectangle in a world full of squares who want to kill you. The game will work as follows:

The final product will look something like this:

I Hate Squares Screenshot

I Hate Squares Screenshot

I Hate Squares Screenshot

We are developing for mobile so we must consider opportunities and challenges that are unique to mobile when designing our game. Here's a few things to think about:

Applying these considerations to our game, the most prominent issue that comes to mind is movement. Our character will be able to move in any direction - this would be easy to achieve with the use of the arrows on a keyboard but we don't have access to that. So our options may include:

We will also need to deal with the changing size of devices and how that will affect our game. Fortunately this should be reasonably easy to cope with since our game space does not have to be any specific size.

We will discuss and deal with these issues as we get to them, but it's good to think of these things and consider potential approaches from the start.

Let's Get Started

Ok, enough talking - let's get our hands dirty. In this first lesson we're going to set up a skeleton for our Phaser game. We will be building a generic skeleton that can be used for just about any game.

The game in the Making Your First Phaser Game guide only consisted of a single main state, we will be adding an additional 4 states giving us a total of 5. A state in Phaser is basically a JavaScript object that runs a specific state that the game is in. For example one state might be the games title screen, another would be the game itself, and another would be the game over screen. We also might have different states for different levels, e.g: Level 1, Level 2, Level 3 etc. But we also have states for other things like booting and loading the game. The states we will be creating for our skeleton application are:

Boot

This is our first state, and it will be invoked as soon as our game is launched. We won't be using this state for a lot, just to initially scale the dimensions of the game to the appropriate size and then call our second state.

Preload

Preload is our second state and will be used to load in all the assets (images, audio, etc.) our game needs to function. The next state won't be triggered until all the assets are ready.

GameTitle

This state will be used to display the games title screen. Usually we will display the title of the game here, maybe some graphics and a 'Play' or 'Start' button to take the player into the game. Perhaps we might even want to add an 'Instructions' button in here too that could open up it's own Instructions or Tutorial state.

Main

Finally we get into the fun part. The main state will contain our actual game code.

Game Over

Eventually our player is going to die or win, at which point they will arrive in this state. We will use this screen to display a score and offer them the opportunity to start a new game.

Any good code base is modularised in some way. In web development we separate our HTML, CSS and JavaScript into separate files - this makes our code more readable and organised, and makes it easier to update in the future. In Phaser, rather than having all the code in one giant 'main' state we separate it out into different states.

Setting up the application

By now you should already have a web server like XAMPP set up on your computer and you should also have downloaded the phaser.min.js source file. We will start by creating a new a new folder called ihatesquares in the web server root, which would look something like:

C:\xampp\htdocs\ihatesquares

or

/Applications/XAMPP/htdocs/ihatesquares

Create a folder called I Hate Squares inside of your htdocs folder

Now inside of that folder we're going to create two more folders:

Create an assets and js folder inside of your ihatesquares folder

Once you've created those folders, you will need to include the phaser.min.js file in your project:

Copy phaser.min.js into the js folder you just created

The structure of your folder should look like this:

Phaser Project Structure

Now we will get onto creating each of the states we just mentioned.

Creating the Boot State

Create a file called boot.js inside of your js folder and add the following code to it:

var Boot = function(game){

};

Boot.prototype = {

    preload: function(){

    },

    create: function(){
        this.scale.scaleMode = Phaser.ScaleManager.SHOW_ALL;
        this.scale.setScreenSize(true);
        this.game.state.start("Preload");
    }
}

Currently the only role this state has is to set the screen size to fit the device that we are on, and then trigger our "Preload" state. This state will run when the game is first started and will only run once.

Detour!

Although this course is not intended to be an introduction to the JavaScript language, I feel it would be worth explaining the structure used in this code example. This is the basis for all of our states so it's important to understand what is going on. I would recommend reading through this but if you really just want to keep building the game then feel free to skip over it and come back later.

NOTE: If you are new to JavaScript you can still probably make your way through this course without too much difficulty (assuming you have some programming knowledge). It'll definitely help to get the basics of JavaScript down though - try this to get started.

In JavaScript a function acts like an object, and it can contain methods (functions) and properties. An important property of these function objects is prototype. prototype is a property that is available whenever you create a new function, however it will initially be an empty object. We can add methods and properties to this empty object which can be accessed through the object.

In the example above, we are overwriting the entire prototype object and supplying two methods. This would be similar to doing the following (without overwriting):

Boot.prototype.preload = function(){

}

Boot.prototype.create = function(){

}

We will never have to do this in Phaser, but for the sake of an example we could call the preload method of boot with the following code since we have it defined in the prototype:

Boot.preload();

Ok, I know this is dragging on a little bit and you probably want to get into making games - just bare with me a little longer. Now we could also achieve a similiar effect by creating an object like this:

var Boot = function(game){

     this.preload = function(){

     }

     this.create = function(){

     }

}

Now when we call boot.preload() it will first look for a function called 'preload' defined within the object as we have above. If it can not find it within that object it will look at the objects prototype for the function (where we originally defined it).

So what's the difference?? Can't we just pick one method and move on with our lives?

There's two main reasons we are using the prototype method:

  1. If we create an instance of an object and try to call one of its methods, as I mentioned before it will first look within that instance and then it will look at the prototype. Since all instances will share the same constructor and thus the same prototype, if we modify one of the methods through the prototype:
Boot.prototype.preload = function(){
     console.log("we changed something!");
}

Then this method will effect all methods that have already been created. If we were to define the methods directly on the object then we would need to modify the method for each instance that has already been created.

  1. It is also better performance wise. Methods defined directly on the object will be created every time a new instance of that object is created, whereas methods defined on the prototype are created once and then inherited by each instance.

All of the above was not at all essential for you to know to learn Phaser. If you don't really get it (I know I didn't for a long time, and I still probably don't) then don't worry too much, I just want to explain why we are doing things that may seem a little out of the ordinary rather than asking you to take them at face value. As Elon Musk stated on learning recently:

"It is important to view knowledge as sort of a semantic tree -- make sure you understand the fundamental principles, ie the trunk and big branches, before you get into the leaves/details or there is nothing for them to hang on to." - Elon Musk

Back to game making!

Seriously now, we're going to get back into the game making:

Create the Preload State

Create a file called preload.js and save it in your js folder, then add the following code to it:

var Preload = function(game){};

Preload.prototype = {

    preload: function(){ 

    },

    create: function(){
        this.game.state.start("GameTitle");
    }
}

Eventually we will be adding some more code to the preload method of the Preload state, which will load in all the assets we require for our game. Like our Boot state, Preload also has a create method that will run once when the state is created. In this case all we are doing is using it to call our next state.

Create the GameTitle State

Create a file called gametitle.js and save it in your js folder, then add the following code:

var GameTitle = function(game){};

GameTitle.prototype = {

    create: function(){

    },

    startGame: function(){
        this.game.state.start("Main");
    }

}

Again, GameTitle also has a create method that will run when it is created. We will use this to create our game title screen which will contain some graphics and some form of 'Start' button that will be used to start the game when the player is ready. In this case we don't call our next state, Main, until we receive input from the user. So we will trigger the 'startGame' method from somewhere within the create method (in most cases we would trigger the startGame() function when a user taps on a button).

Create the Main State

Create a file called main.js and save it in your js folder, then add the following code:

var Main = function(game){

};

Main.prototype = {

    create: function() {

    },

    update: function() {

    },

    gameOver: function(){
        this.game.state.start('GameOver');
    },

};

This is the state where most of the magic happens, and it is responsible for running the actual game itself. We have the usual create method as we did in our other states, and a gameOver method that we will use to trigger the next state when we are ready, but there is one method here we haven't added to the others. The update method will constantly loop every frame refresh. We will create the initial state of our game in the create method, but will place a lot of the logic for our game in the update method.

The update method may run every, let's say for example, 100 milliseconds - so 10 times every second. Inside of here we might test for things like:

"Is the player currently colliding with an enemy?"

"Is the user pressing the space bar button?"

"Is the player currently moving?"

Then we can act upon what is currently happening in the game. If the player is colliding with the enemy then we may want to trigger the gameOver method, or maybe we want to instead take away one life from the player. If the player is holding down the space bar button maybe we want to make the player fly until they let go, and so on.

  1. Create the GameOver State:

Create a file called gameover.js and save it in your js folder, then add the following code:

var GameOver = function(game){};

GameOver.prototype = {

    create: function(){

    },

    restartGame: function(){
        this.game.state.start("GameTitle");
    }

}

Finally we've arrived at our final state, and there's no surprises here. We simply have our usual create method which will be used to create the Game Over screen, as well as an additional method that will allow the user to restart the game. When we leave a state and come back to it again later, it will be completely refreshed. So when we eventually call:

this.game.state.start("Main");

again, our create method in the main state will run again, creating a fresh new game. It is possible to create some persistence throughout games (perhaps giving the user the ability to collect coins which they can spend) through using local storage, but we will talk about that later.

  1. Bringing it all together with index.html

As is the case with a normal website, the first file that is loaded is our index.html file. We will use this file to initialise our Phaser game, load in our javascript files (our states) and to call our initial state.

Create a file called index.html and place it in the root folder of your project. Then add the following code:

<!doctype html> 
<html lang="en"> 
<head> 
    <meta charset="UTF-8" />
    <title>I Hate Squares</title>
    <script type="text/javascript" src="js/phaser.min.js"></script>
    <script type="text/javascript" src="js/boot.js"></script>
    <script type="text/javascript" src="js/preload.js"></script>
    <script type="text/javascript" src="js/gametitle.js"></script>
    <script type="text/javascript" src="js/main.js"></script>
    <script type="text/javascript" src="js/gameover.js"></script>
    <style type="text/css">
        body {
            margin: 0;
        }
    </style>
    <script type="text/javascript">
        (function() {

                //Create a new game that fills the screen
                game = new Phaser.Game(window.innerWidth * window.devicePixelRatio, window.innerHeight * window.devicePixelRatio, Phaser.AUTO);

                //Add all states
                game.state.add("Boot", Boot);
                game.state.add("Preload", Preload);
                game.state.add("GameTitle", GameTitle);
                game.state.add("Main", Main);
                game.state.add("GameOver", GameOver);

                //Start the first state
                game.state.start("Boot");

        })();
    </script>
</head>
<body>
</body>
</html>

The embedded JavaScript code above is responsible for initialising our game (this will run as soon as the page is loaded). To create an instance of a Phaser game we call Phaser.Game() and supply it with the width and height of our game, as well as which rendering engine we want to use.

We don't just supply a width and height though, we also get the devicePixelRatio of the device we are running on. This is not always necessary but since we are creating games for a mobile device we do this so the game scales properly. We can get the width and height of the space we have to work with by using window.innerWidth and window.innerHeight (this will make the game full screen). The reason we multiply it by the pixel ratio though is because different devices can have different pixel densities. Take Apple's Retina displays for example, if we were to put this game on an iPhone 5 and tried to use window.innerWidth and window.innerHeight we would get a size of:

320 x 568

But the actual size of the screen is 640 x 1136. This is because the iPhone 5 has a device pixel ratio of 2, so if we multiply the innerWidth and innerHeight by 2 we get the actual screen size of 640 x 1136.

As I mentioned, we also supply which rendering engine we want to use to the Phaser.Game() call. This can either be WebGL or Canvas, if we set it to AUTO then it will use WebGL if available, but fall back to Canvas if it is not available.

Once we have initialised our game, we add all of our states to the game:

game.state.add("Boot", Boot);
game.state.add("Preload", Preload);
game.state.add("GameTitle", GameTitle);
game.state.add("Main", Main);
game.state.add("GameOver", GameOver);

and trigger our first state with the following code:

game.state.start("Boot");

This will then start the chain reaction of calling the states we created before: Boot calls Preload which calls GameTitle which calls Main which calls GameOver which then calls GameTitle once more.

This brings us to the end of this lesson. Now we have a blank skeleton application that you could use for just about any game. Your project structure should look something like this:

Phaser Project Structure

Remember that all of the code for each lesson is available in the download package you would have received. So if you have any trouble throughout this course make sure to check your code against the source code for the lesson you're up to. I recommend that you don't just copy and paste though and that you actually code it yourself, you'll learn a lot more this way.

In the next lesson we will get into actually building our own game!

Homework Tasks

Copyright © 2015 Joshua Morony | Privacy Policy | Contact

This is a preview of Mobile Development for Web DevelopersLEARN MORE