Getting Started With HTML5 Game Development: Phaser

From today lets learn HTML5 browser game development – applies both to desktop as well as mobile browsers. You’ll be able to build mobile game apps and launch it to play store or app store.

phaser logo

Phaser is an open source HTML5 game framework created by Photon Storm. It’s designed to create games that will run on desktop and mobile web browsers. A lot of focus was given to performance inside of mobile web browsers, a growing and important area of web gaming.

Video Tutorial List At One Place:
Phaser Video Tutorial List: Game Framework

In this introductory video you’ll be learning:
1. How to get started with Phaser.
2. Download the library and incorporate it into your new game project.
3. Running the game inside the server – in our case, we’re making use of Node server.
4. Quick starter guide to initiate and run the game project.
5. Placing the image in cache – using preload method.
6. Placing the cached/preloaded image(sprite) on to the game stage/container – using create method.
7. Setting the game stage / container background color.
8. Resizing the stage/container and trick to make use of entire device screen for our game.

Phaser Version: 2.4.9 (immediately 2.5.0 was released, so from tomorrows video we’ll be using 2.5.0)
OS used for Demo: Windows 10
Server used: Node Server


[youtube https://www.youtube.com/watch?v=SWEiIxAciUw]

YouTube Link: https://www.youtube.com/watch?v=SWEiIxAciUw [Watch the Video In Full Screen.]



Node Server
1. Node.js Video Tutorial List
2. Express Web Framework: Node.js

HTML File – index.html

< !DOCTYPE html>
<html>
<head>
<script type="text/javascript" src="javascripts/library/phaser.js"></script>
</head>
<body>
     <div id="gameContainer"></div>
</body>
</html>

Start with the HTML5 doc type as the first line, as Phaser is a HTML5 Game framework. Then you need to download the phaser library, and include it inside your project. If you’re using Node server, then place the library file and all the files inside the public directory. Use phaser.js file (the unminified version) for development and phaser.min.js file (the minified version) while pushing the code to production server.

You can optionally place a div container to render the game or the game engine will consider entire html body as game stage or container. In our case, for demonstration we’ve placed a div with id gameContainer and we’ll make phaser to use this to render the game objects.

JavaScript Code – Game Code

    var game = new Phaser.Game(window.innerWidth, window.innerHeight, 
                               Phaser.AUTO, 'gameContainer', {
                   preload: preload, create: create
               });
    function preload(){
        game.load.image('logo', '/images/logo.png');  
    }
    function create(){
        game.add.sprite(10, 100, 'logo');  
        game.stage.backgroundColor = '#e7e7e7';
    }

Create a game object with the help of Phaser.Game class. You need to pass the game stage width and height, then we can let Phaser decide whether to user WebGL or canvas to render the game – using Phaser.AUTO property. Phaser gives priority to WebGL, if it’s not present then it’ll make use of Canvas. Next we can optionally specify the game container id, and then the game code.

In this example I simply wrote the code and directly passed it as an argument. This works. And this is ok, if the game code is small. But in big game projects we need to follow modularity – which I’ll teach in my next video tutorial.

A valid Phaser state must have atleast one of these methods – preload, create, update.

preload method: is used to load all the game assets. Once loaded, these assets are stored in cache.
create method: here we make use of cached assets and present them on our game stage or container. We also create other objects needed for our game.
update method: this method is repeatedly called and our game objects are constantly updated to create movements or update the game objects or objectives!

In above code, inside preload method, we are using game object and loading a image and giving it a name called logo, by making use of game.load.image() method. First parameter is a name we give it to the image or sprite as we’ll start calling it from now. The second parameter is the path of the actual image – this can even be a remote server URL. Next we place this image on our game stage using game.add.sprite() method, by using create method. I’ve also shown you how to change the background color of the stage by using game.stage.backgroundColor property.

Full Screen Game
Often time when we’re developing game for mobile device(android or iOS game app), we would want to use full screen of the device – we can achieve this by passing window.innerWidth and window.innerHeight parameter while creating game object – as shown in the code – var game = new Phaser.Game(window.innerWidth, window.innerHeight, Phaser.AUTO);

Full source code

< !DOCTYPE html>
<html>
<head>
<script type="text/javascript" src="javascripts/library/phaser.js"></script>
</head>
<body>
<div id="gameContainer"></div>
 
<script type="text/javascript">
    var game = new Phaser.Game(window.innerWidth, window.innerHeight, 
                               Phaser.AUTO, 'gameContainer', {
                    preload: preload, create: create
                });
    function preload(){
        game.load.image('logo', '/images/logo.png');  
    }
    function create(){
        game.add.sprite(10, 100, 'logo');  
        game.stage.backgroundColor = '#e7e7e7';
    }
</script>
</body>
</html>

In my next video tutorial I’ll show how to write modular code to handle big game projects – I’ll show it by using same code we used today, so that you’ll feel somewhat familiar.

Please make sure you download the phaser library and try it yourself – this looks like a small example, but worth trying, if you’re a beginner. Stay subscribed, more Phaser video tutorials are on the way.

Download Attribute: HTML5

In this video tutorial we’ll show you how we can add download attribute and make the UX(User Experience) little better!

Related Read: HTML5 and CSS3 Video Tutorial List

We’ve seen so many times that a PDF file available for download opens up in the browser once the link is clicked. Same way the rar files, zip files, image files etc. We could add download attribute and fix this simple issue.

HTML5: Download Attribute with Value

1
2
3
 <a href="Picture1.jpg" download="book.jpg">
    Download Book Cover
 </a>

Once we add download attribute to the anchor tag, once someone clicks on the link, the linked resource starts to download, instead of opening in the browser.

The value, if present, to download attribute will be used to replace the original name of the resource file linked in the anchor tag.

Download Attribute: HTML5


[youtube https://www.youtube.com/watch?v=Wg6bMQ9leMQ]

YouTube Link: https://www.youtube.com/watch?v=Wg6bMQ9leMQ [Watch the Video In Full Screen.]



Full Free Code: HTML5 Download Attribute with Value

1
2
3
4
5
6
7
8
9
10
11
12
13
< !doctype html>
<html>
<head>
<title>Download Attribute</title>
</head>
<body>
 
 <a href="Picture1.jpg" download="book.jpg">
    Download Book Cover
 </a>
 
</body>
</html>

Make sure you have the doctype of html5(First line in above code).

progress Element: HTML5

Lets look at the progress element of HTML5.

progress-element-html5-progress-bar

You could implement this progress element of HTML5 with the file upload or the user form filling etc, to indicate the amount of upload or the profile completion.

HTML file
index.html

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
< !DOCTYPE html>
<html>
<head>
<title>progress Element: HTML5</title>
<link href="myStyle.css" rel="stylesheet"/>
</head>
<body>
 
<form>
<label>Progress: </label>
 <progress value="50" max="100">50%</progress>
</form>
 
</body>
</html>

Here we have a progress element, with 100 as max and 50 as it’s value. This way, the progress bar indicates that the progress is 50% complete. Also there is a text between the progress tag, which is used as a fall back text for browsers which do not yet support progress element of HTML5.

CSS file associated with this is same as present at pattern and title Attribute of Form Field: HTML5

progress element – progress bar: HTML5


[youtube https://www.youtube.com/watch?v=s1tfYfCpZx8]

YouTube Link: https://www.youtube.com/watch?v=s1tfYfCpZx8 [Watch the Video In Full Screen.]



Change the number present in value and max attribute and look at the visual effect/indication of the progress on the browser.

Note: In real time application development, you could fetch the numbers for value and max attribute dynamically using JavaScript. This way, the effects will be real and it creates the illusion that the progress is being made!

callback methods / anonymous functions: jQuery

Today lets see how callback methods or anonymous functions work. We also show you the anatomy of callback methods.

callback-method-anonymous-function-javascript-jquery-nodejs

callback methods are very important for achieving asynchronous way of coding.

HTML file
index.html

1
2
3
4
5
6
7
8
9
10
11
12
13
14
< !DOCTYPE html>
<html>
<head>
<title>callback or anonymous function</title>
<script src="jquery-1.10.2.min.js"></script>
<script src="myScript.js"></script>
</head>
<body>
 
<p></p>
<div></div>
 
</body>
</html>

Here we have included jQuery library and myScript.js We also have a paragraph tag and a div tag, to be filled with some data by myScript.js file.

JavaScript file
myScript.js

1
2
3
4
$(document).ready(function(){
 $("p").hide("slow");
 alert("Stop!");
});

Here the paragraph hide is called and before it finishes hiding, alert is called and every other operation of the webpage is halt until the user responds to the alert window. But if we want the paragraph to be hidden first and only after the paragraph is completely hidden we need to call the alert, in such case use callback methods as shown below:

JavaScript file: callback method
myScript.js

1
2
3
4
5
$(document).ready(function(){
 $("p").hide("slow", function(){
        alert("Stop!");
 });
});

If you want multiple things to occur after hiding the text(in above case) , you can nest the callback methods.

Anatomy of callback methods
JavaScript file: callback method
myScript.js

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
$(document).ready(function(){
eat("pizza", "cola", function(){
$("div").html("I had my food!");
});
 
});
 
function eat(food, drink, callback)
{
$("p").html("I ate "+food+" and had a "+drink);
 
if(callback && typeof(callback) === "function" )
{
callback();
}
 
}

Here we have a method called eat, which takes 3 parameters. First two are variable type and the 3rd parameter is a function type argument.

Once the page loads, we call eat method and pass pizza, cola and a callback method to it. After the first 2 variable values are displayed, eat method checks if the 3rd parameter is actually present and is a function – if so, it’ll call the function. So, the callback method is called after its preceding arguments are processed.

Anatomy and Working of Callback methods / anonymous functions


[youtube https://www.youtube.com/watch?v=lIPOER59ZSY]

YouTube Link: https://www.youtube.com/watch?v=lIPOER59ZSY [Watch the Video In Full Screen.]



Examples:
1. If we have calls to Facebook API, Twitter API and Google Finance API’s: Using JavaScript(jQuery or nodejs) we could send the request to all these API’s concurrently and not worry much about its response time. Once any of these API’s respond, the corresponding callback methods are called. So while these scripts are executed, it binds the callback methods to its calls, and then stops worrying about its response!

2. Many ad networks have implemented asynchronous ad codes, since these codes use callback methods and there is no need for the webpage to wait until the ad server responds. If and when the ad server responds with an ad, the page or the ad spot is filled with the ad.

color Input Type: HTML5

color input type fields expect the user to pick the color from the color palette. Once the user selects the color its corresponding hexadecimal value is being stored in the input field.

form-input-type-color-type-html5

Demo

There are jQuery plugins to accomplish this task, but with HTML5 we need not use any plugins to accomplish this!

HTML file
index.html

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
< !DOCTYPE html>
<html>
<head>
<title>color Input Type: HTML5</title>
<link href="myStyle.css" rel="stylesheet" />
<script src="myScript.js"></script>
</head>
<body onload="fetch()">
 
<div>
<label for="color">Color pick: </label>
 <input name="color" type="color" id="get" onchange="fetch()"/><br />
<label for="hexa">Hex Code: </label>
 <input name="hexa" type="text" id="put"/><br />
</div>
 
</body>
</html>

Here we have 2 input fields of type color and text respectively. Once the user selects a color from the color palette, the corresponding hexadecimal value is shown in the text input type field.

JavaScript file
myScript.js

1
2
3
4
5
function fetch()
{
var get = document.getElementById("get").value;
document.getElementById("put").value = get;
}

Once the fetch method is called: it fetches the value present in the (color)input field and assigns it to text input field.

CSS file associated with this is same as present at pattern and title Attribute of Form Field: HTML5

Form Input Type – color: HTML5


[youtube https://www.youtube.com/watch?v=MiCOVDrVH44]

YouTube Link: https://www.youtube.com/watch?v=MiCOVDrVH44 [Watch the Video In Full Screen.]



Note: In real production server, you need not use two input fields as shown in this video tutorial. You can simply make use of the color input type and once you submit the form, you’ll get hexadecimal code value in place of the color input field. If you have a large audience still using Internet Explorer or other older browsers, then you can use jQuery plugin to accomplish the same task across all major browsers.