How to Make a Toddler's Game with the Phaser HTML5 Framework

Kids love technology. I'm sure you've all seen either in person or on video how babies can use seamlessly tablets and phones. The kids who have come to be known as the generation moth have been exposed to mobile computing since birth.

A lot of the games these toddlers play with are actually very simple to make and can be good game development projects.

In this tutorial I'm gonna make a farm animal slider game vaguely inspired in Fisher-Price's Animal Sounds for Baby for Android* using the HTML5 Phaser library.

Phaser is a fun, free and lightweight HTML5 2D game framework created by Richard Davey and supported by a great community of developers who usually hang out at the HTML5 GameDevs forums.

Other Phaser Learning Resources

Some other Phaser tutorials I’ve authored and co-authored:

Tutorial Source Code and Asset Files

You can grab the tutorial source code and game assets in a ZIP file from here. You can also clone the Github repo. If you want to see the finished product go here to see it live.

What about the game artwork?

All the artwork of this game was created by my company Zenva and you can use it for commercial and non-commercial projects, no attribution required (although if you make the next Candy Crash with it please buy me a mansion).

Learning Objectives

In this tutorial we will make a cross-platform toddlers game with Phaser and we'll export it to Android using Apache Cordova* and the Intel® XDK.

Some of the concepts we'll cover:

  • Working with sprites: anchor point, rotation, flipping, scaling.
  • Handling user input.
  • Screen scaling to adjust the game to different screen sizes.
  • Working with groups in Phaser.
  • Tweening and sprite animations.
  • Adding text.
  • Adding audio.
  • Exporting a HTML5 game as a native Android application.
  • Putting it all together to make a toddlers game.

Tutorial Requirements

This tutorial assumes you have basic JavaScript skills. If that is not the case feel free to check my JavaScript course at Zenva Academy for a very fast-paced learning experience.

No prior experience with Phaser, Cordova, Android or game development in general is required to follow this tutorial.

Games built with Phaser can’t be ran by just double clicking on the index.html file. They need to be run using a web server. For a Phaser game that doesn’t include any Cordova API usage you are good to go with the usual web server alternatives such as WAMP for Windows , MAMP on the Mac , Python’s simple HTTP server or Node.js http-server package.

Also, some code editors such as the Intel XDK and Brackets come with in-built web servers so you don't have to install any external ones.

Hola World

The skeleton of our Phaser project will be an index.html file that includes the Phaser library and our custom script. These files will look like so:

index.html


<!DOCTYPE html>
<html>

	<head>
		<meta charset="utf-8" />
		<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, minimum-scale=1, user-scalable=no" />
		<title>Learn Game Development at ZENVA.com</title>
		<script type="text/javascript" src="js/phaser.js"></script>		
		<style>
		  body {
		    padding: 0px;
		    margin: 0px;
		    background: black;
		  }
		  </style>
	</head>

	<body>  
		<!-- include the main game file -->
		<script src="js/main.js"></script>
	</body>
</html>


And main.js:


//this game will have only 1 state
var GameState = {
  //initiate game settings
  init: function() {
  },

  //load the game assets before the game starts
  preload: function() {    
  },

  //executed once after everything is loaded
  create: function() {
  },

  //this is executed multiple times per second
  update: function() {    
  } 

};

//initiate the Phaser framework
var game = new Phaser.Game(640, 360, Phaser.AUTO);

//add the state to the game object
game.state.add('GameState', GameState);

//launch the state
game.state.start('GameState');


If you are using the latest Intel XDK, you can easily generate a new hello world project for Phaser by going to New Project - Start with a Template - then select Phaser from the list of options. Our starter files and folder structure will look slightly different though.

When loading index.html in your browser using a web server (as explained above), if you open your browser's console you should see that Phaser was successfully initiated.

Sprites

Images or “sprites” are the bread and butter of 2D games. Phaser uses sprites to represent backgrounds, game characters and pretty much all images in a game. Before we dive into creating our farm animals game let's look at some examples of what you can do with sprites.

Preloading textures

Before you can use a sprite you always have to preload the image file. Loading an image from the disk takes time, whereas loading an image from the device RAM memory is super fast. The preloading of the game assets is nothing but loading everything from the disk and putting it into the RAM memory, so that when the image or asset is needed, it can be displayed instantly.

Have you noticed how sometimes a website is partially loaded and you can see most of the content except for some images? That is because those images are being loaded from the server. This is all right for a website but on a game it would be unacceptable! (just try to imagine your favorite game but with a black square instead of the main character, as it hasn't been loaded yet).

So what we do is preload the images and other game assets such as sound files in the preload() method of our GameState object, like so:


preload: function() {
    this.load.image('background', 'assets/images/background.png');
    this.load.image('chicken', 'assets/images/chicken.png');
}


this.load is accessing an object called the Loader which is initiated by Phaser. This object has different methods to load different types of game assets. You can learn more about it in the documentation. The first parameter is the key of our asset, you can type there anything you want as long as you don't call two assets by the same key. We will use the key later in the code to refer to that particular asset.

Showing a sprite

To show these two sprites we'll add some code to the create() method of GameState, which is executed once after the preloading phase has finished.


//executed once after everything is loaded
  create: function() {
      this.background = this.game.add.sprite(0, 0, 'background');      
      this.chicken = this.game.add.sprite(100, 100, 'chicken');
  },


The sprites are located in the specified coordinates X and Y. The coordinate system starts on the top-left corner of the game world. Y is positive downwards and X is positive to right.

Showing a sprite with the code shown above will look as follows:

Anchor point

The point of the sprite that is placed in location x,y is its anchor point. By default, the anchor point of a sprite is its top-left coordinate. So if I set the location of a sprite to (10,10) that means that the top-left of the sprite will go on that position.

If you rotate a sprite, the rotation will occur around its anchor point. Also, if you scale a sprite, the sprite will grow or shrink but the anchor point will stay on the same location.

Sometimes you'll want to change the anchor point of a sprite. For example, you may want to specify the location of the sprite by its center point. You can do that as follows (after showing the sprite):


//change anchor point to middle
//can also just type: this.chicken.achor.setTo(0.5);
this.chicken.anchor.setTo(0.5, 0.5);


Rotating a sprite

You can easily rotate a sprite by changing the angle property. The rotation occurs around the anchor point (in this case the middle of the sprite). The value is given in degrees:


this.chicken.angle = 90;


Scaling a sprite

You can easily scale a sprite up or down by accessing the scale property (remove the rotation code):


this.chicken.scale.setTo(3,1); //scaling 2x on the X direction and keeping the same scale on the Y direction



this.chicken.scale.setTo(0.5) //scaling the chicken in 50% on both x and y


Flipping a sprite

If you want to flip a sprite on X or Y you can just use the scale property but with negative values. If you set it to -1 on X for example, the sprite will flip on X and won't change its size. If you use a negative number different than -1 you will be doing both flipping and changing the dimensions of the sprite.


this.chicken.scale.setTo(-1,1); //flip on x


Placing a sprite on the center of the world

The easiest way to do this is to set the anchor point to the middle of the sprite, and place it like so:


//create the sprite on the center of the world
this.chicken = this.game.add.sprite(this.game.world.centerX, this.game.world.centerY, 'chicken');
      
//change anchor point to middle
this.chicken.anchor.setTo(0.5, 0.5);


You can always change the location of a sprite by accessing the x and y properties of the sprite.

For more information on the Sprite class and the methods we used here check out the Sprite documentation.

Making the game fit the screen size

No matter what platform(s) you are developing for, there will multiple screen sizes and aspect ratios. That is just the world we live in. This used to be a nightmare for HTML5 game developers but most of the main game frameworks have options to work with this. Phaser is not the exception and comes with a few different options to deal with this and make our game work on different devices. This is all handled by an object called the Scale Manager.

Our game will resize so that it fits the size of the screen, keeping the same aspect ratio. This is a mode for the Scale Manager called SHOW_ALL. We can set this up in our init() method:


//initiate game settings
  init: function() {
    //scaling options
    this.scale.scaleMode = Phaser.ScaleManager.SHOW_ALL;

    //have the game centered horizontally and vertically
    this.scale.pageAlignHorizontally = true;
    this.scale.pageAlignVertically = true;
  },


Adding the arrows

Let's add the arrows that will be used to switch the current animal. When the user clicks on these arrows, the current animal will move either to the left or right, and a new animal will take its place in the middle of the screen.

For now we are just gonna add the sprites for the arrows with some custom properties. Start by preloading the texture in the preload method:


this.load.image('arrow', 'assets/images/arrow.png');

Now, in create, add the following:

//left arrow
this.leftArrow = this.game.add.sprite(60, this.game.world.centerY, 'arrow');
this.leftArrow.anchor.setTo(0.5);
this.leftArrow.scale.x = -1;
this.leftArrow.customParams = {direction: -1};

//right arrow
this.rightArrow = this.game.add.sprite(580, this.game.world.centerY, 'arrow');
this.rightArrow.anchor.setTo(0.5);
this.rightArrow.customParams = {direction: 1};


What we are doing is simply creating two sprites, one for each arrow. They both use the same texture which we called “arrow”. See how we are positioning at the center of the game world on Y, set the anchor point to the middle of the image and use the scale property to flip the first arrow so that it's pointing to the left.

Custom sprite parameters

I want to create a custom parameter for the arrow sprites that indicates the direction in x that they are representing. You could just do this.rightArrow.anythingHere to define a custom property, but I prefer to save all custom properties in a single object which I'm calling “customParams”. Why would I do that? Well, what if you are not fully familiar with Phaser and you want to save a property called say “scale”. As we know, scale is already a property of sprites, so if we replaced it with some other value things will go wrong and it'll be hard to debug. In order to avoid these conflicts, I prefer to just save all custom data in its own object that I know it's not present in a sprite.

User input

We have now the arrows and a chicken in the middle. Later on we won't have this hard-coded chicken in there, but a group of animals. For now we'll keep this chicken so that I can show you how to handle user input.

Let's make the chicken clickable:


this.chicken = this.game.add.sprite(this.game.world.centerX, this.game.world.centerY, 'chicken');

//change anchor point to middle
this.chicken.anchor.setTo(0.5, 0.5);

//enable input so we can touch it
this.chicken.inputEnabled = true;    

//only trigger click on non-transparent areas of the sprite
this.chicken.input.pixelPerfectClick = true;

//callback function for click events
this.chicken.events.onInputDown.add(this.animateAnimal, this);  


We need to create the animateAnimal method in our GameState object. This is where we'll start an animation and play a sound:


//play animal animation and sound
  animateAnimal: function(sprite, event) {
    console.log('animate animal and play sound');
  },


Let's enable input for both arrows:


//left arrow
this.leftArrow = this.game.add.sprite(60, this.game.world.centerY, 'arrow');
this.leftArrow.anchor.setTo(0.5);
this.leftArrow.scale.x = -1;
this.leftArrow.customParams = {direction: -1};

//left arrow user input
this.leftArrow.inputEnabled = true;
this.leftArrow.input.pixelPerfectClick = true;
this.leftArrow.events.onInputDown.add(this.switchAnimal, this);

//right arrow
this.rightArrow = this.game.add.sprite(580, this.game.world.centerY, 'arrow');
this.rightArrow.anchor.setTo(0.5);
this.rightArrow.customParams = {direction: 1};

//right arrow user input
this.rightArrow.inputEnabled = true;
this.rightArrow.input.pixelPerfectClick = true;
this.rightArrow.events.onInputDown.add(this.switchAnimal, this);  


And the switchAnimal stub:


//switch animal, the sprite parameter gives us access to the sprite that was clicked/touched
switchAnimal: function(sprite, event) {
  console.log('switch animal');
}


Now you should see in the console a message when you click in either the arrows or the chicken.

Groups

Working with a collection of sprites is a common use case in game development. Think of a spaceship game where you have multiple enemies. New enemies are created, killed, and they respond in the same way to the environment.

In our farm animals game we'll have a collection of animals. Using the arrow buttons you can move to the next animal or bring back the previous one. To represent these animals we'll use a group.

The specific data of each animal (their name, texture, sound, animation) will be listed an array of objects (which in theory could have been loaded from the web or some storage). Using this data we will create sprites and put them in a group.

So say goodbye to the chicken. We'll be working now with groups. Let's begin by preloading all the images:


preload: function() {    
    this.load.image('background', 'assets/images/background.png');
    this.load.image('arrow', 'assets/images/arrow.png');
    this.load.image('chicken', 'assets/images/chicken.png');
    this.load.image('horse', 'assets/images/horse.png');
    this.load.image('pig', 'assets/images/pig.png');
    this.load.image('sheep', 'assets/images/sheep.png');
  },


In the create method, replace everything before the arrows code by the following:


     //create a sprite for the background
    this.background = this.game.add.sprite(0, 0, 'background');
    
    //data for our animals
    var animalData = [
      {key: 'chicken', text: 'CHICKEN',},
      {key: 'horse', text: 'HORSE'},
      {key: 'pig', text: 'PIG'},
      {key: 'sheep', text: 'SHEEP'}
    ];

    //create a group to store all animals
    this.animals = this.game.add.group();
    
    //populate this group with the animal data
    var self = this;    
    var animal;
    animalData.forEach(function(element){
      //create each animal and save its properties
      animal = self.animals.create(-1000, self.game.world.centerY, element.key, 0);

      //I'm saving everything that's not Phaser-related in an object
      animal.customParams = {text: element.text, sound: 'to be added..'};

      //anchor point set to the center of the sprite
      animal.anchor.setTo(0.5);

      //enable input so we can touch it
      animal.inputEnabled = true;
      animal.input.pixelPerfectClick = true;
      animal.events.onInputDown.add(self.animateAnimal, this);
    });

    //place first animal in the middle
    this.currentAnimal = this.animals.next();
    this.currentAnimal.position.set(this.game.world.centerX, this.game.world.centerY);


Basically what we just did was:

  1. Define all the animal data in a JSON object. This could have been loaded from the web or from a local storage, or procedurally generated for some types of games.
  2. Create a group
  3. Iterate through the animal data to create sprites for each animal and add that to our group
  4. For each one of these sprites, we've enabled touch, set a callback function for when the animal is clicked on.
  5. We pull an animal from the group using the next() method and position that animal in the middle. Groups allow us to navigate them with next() and previous().

You can read and learn more about groups in the Group class documentation.

Navigating the animal parade

Let's implement now the animal switching functionality. When the arrows are clicked, depending on the direction of the arrow, we'll retrieve the “previous” or the “next” animal in the group and show it. The “current animal” (the one that's currently on the center of the screen) will be moved to one side or the other (without animations just yet). Lastly, the animal that just made an entry will be the new “current animal”.

This will be the code for switchAnimal(). When we add the tweening animations we'll go back to this method and update it so that the animals move smoothly.


//switch animal
  switchAnimal: function(sprite, event) {

    var newAnimal, endX;

    //according to the arrow they pressed, which animal comes in
    if(sprite.customParams.direction > 0) {
      newAnimal = this.animals.next();
      newAnimal.x = -newAnimal.width/2;
      endX = 640 + this.currentAnimal.width/2;
    }
    else {
      newAnimal = this.animals.previous();
      newAnimal.x = 640 + newAnimal.width/2;
      endX = -this.currentAnimal.width/2;
    }
    
    //place new animal in the center of the screen
    newAnimal.x = this.game.world.centerX;
    
    //place the current animal in its final location
    this.currentAnimal.x = endX;
    
    //who's the current animal now!
    this


You should be able now to go through the whole animal parade, one way or the other.

Tweening animations

First of all, what is tweening?

Tweening is an animation technique which consists in generating intermediate frames given an initial and a final state. For example, a ball is in position x = 10 at the start and we define that it should be at position x = 100 at the end of a 10 seconds animation. What will happen is that the ball will be moving smoothly from x = 10 until x = 100 during those 10 seconds. We only defined the initial state, the final state and the time duration.

Phaser comes with tweening functionality (check the Tween class from the documentation) and you can tween pretty much any property of a Sprite object, or many of them at the same time.

In our game example we'll use tweening to move the animals from the initial to their final locations. We can specify a callback that is executed when the animation completes.

During the duration of the animation, we want to disable the arrow buttons so that the user can't keep on pressing them while an animation is taking place (give it a try without the arrows disabled and you'll see the result, it's actually quite funny).

Our switchAnimal method will now look like this:


//switch animal
  switchAnimal: function(sprite, event) {

    //if an animation is taking place don't do anything
    if(this.isMoving) {
      return false;
    }

    this.isMoving = true;


    var newAnimal, endX;
    //according to the arrow they pressed, which animal comes in
    if(sprite.customParams.direction > 0) {
      newAnimal = this.animals.next();
      newAnimal.x = -newAnimal.width/2;
      endX = 640 + this.currentAnimal.width/2;
    }
    else {
      newAnimal = this.animals.previous();
      newAnimal.x = 640 + newAnimal.width/2;
      endX = -this.currentAnimal.width/2;
    }

    //tween animations, moving on x
    var newAnimalMovement = game.add.tween(newAnimal);
    newAnimalMovement.to({ x: this.game.world.centerX }, 1000);
    newAnimalMovement.onComplete.add(function()
      {
        this.isMoving = false;
      }, this);
    newAnimalMovement.start();

    var currentAnimalMovement = game.add.tween(this.currentAnimal);
    currentAnimalMovement.to({ x: endX }, 1000);
    currentAnimalMovement.start();

    this.currentAnimal = newAnimal;
  },


As you can see, the process with tween animations is usually:

  1. Define a Tweet object that will take care of the animations
  2. Enter the tween properties and callback function if any.
  3. Start the animation where needed.

Frame animations

Another type of animations we can use are frame animations. For that, we need spritesheets with the different frames of our animations. The spritesheets we'll use are all provided in the source code and asset files.

Let's begin by preloading the spritesheet. Instead of loading the individual images of the animals we'll load the spritesheets and specify their dimensions and number of frames:


//load the game assets before the game starts
  preload: function() {    
    this.load.image('background', 'assets/images/background.png');
    this.load.image('arrow', 'assets/images/arrow.png');
    this.load.spritesheet('chicken', 'assets/images/chicken_spritesheet.png', 131, 200, 3);
    this.load.spritesheet('horse', 'assets/images/horse_spritesheet.png', 212, 200, 3);
    this.load.spritesheet('pig', 'assets/images/pig_spritesheet.png', 297, 200, 3);
    this.load.spritesheet('sheep', 'assets/images/sheep_spritesheet.png', 244, 200, 3);
  },


Remember that asset loading is done by the Loader class, make sure you familiarize yourself with its documentation.

In our create() method, we'll create animations for each sprite, so that we can play these animations later. Also, notice how when we define the sprite we add now another parameter at the end (which is taking the value of 0). This is to specify which frame of the spritesheet we want to grab. Frame 0 is the first one, counting from left to right.


animalData.forEach(function(element){
      //create each animal and save its properties
      animal = self.animals.create(-1000, self.game.world.centerY, element.key, 0);

      //I'm saving everything that's not Phaser-related in an object
      animal.customParams = {text: element.text};

      //anchor point set to the center of the sprite
      animal.anchor.setTo(0.5);

      //create animal animation
      animal.animations.add('animate', [0, 1, 2, 1, 0, 1], 3, false);

      //enable input so we can touch it
      animal.inputEnabled = true;
      animal.input.pixelPerfectClick = true;
      animal.events.onInputDown.add(self.animateAnimal, this);
    });


When defining the animation: animal.animations.add('animate', [0, 1, 2, 1, 0, 1], 3, false);

See how it's attached to the sprite “animal”. We give our animations a key so that we can refer to them later in the code (in this case “animate”). The second parameter is an array with the order in which the frames will be displayed, so for example in this case the frame 0 will be shown first, then frame 1, etc. The third parameter is the frames per second (how many frames are to be shown in 1 second), in this case 3. The “false” at the end stands for the autoloop option. If that's set to true, the animation will repeat itself upon completion (false is the default value, but I wanted to make it explicit to show you).

We will animate our animals when touched. It's time to add some code to our animateAnimal method:


//play animal animation and sound
animateAnimal: function(sprite, event) {
    sprite.play('animate');
},


Adding sound

Working with sound is not very different than working with images and other game assests. We need to start by preloading them in preload():


this.load.audio('chickenSound', ['assets/audio/chicken.ogg', 'assets/audio/chicken.mp3']);
this.load.audio('horseSound', ['assets/audio/horse.ogg', 'assets/audio/horse.mp3']);
this.load.audio('pigSound', ['assets/audio/pig.ogg', 'assets/audio/pig.mp3']);
this.load.audio('sheepSound', ['assets/audio/sheep.ogg', 'assets/audio/sheep.mp3']);


We are loading both the mp3 and ogg files of the sounds. At least by the time of this writing there is no cross-platform compatible format for audio in HTML5. Mp3 and ogg will give you support for all the main platforms. In order to convert files from one format to another you can use the free Audacity tool, available for Linux, Windows and Mac.

Let's add the keys of these sound assets to our animalData array, and create sound objects for each animal. We'll pass these objects to the “customParams” property of each sprite:


//group for animals
    var animalData = [
      {key: 'chicken', text: 'CHICKEN', audio: 'chickenSound'},
      {key: 'horse', text: 'HORSE', audio: 'horseSound'},
      {key: 'pig', text: 'PIG', audio: 'pigSound'},
      {key: 'sheep', text: 'SHEEP', audio: 'sheepSound'}
    ];

    //create a group to store all animals
    this.animals = this.game.add.group();

    var self = this;    
    var animal;
    animalData.forEach(function(element){
      //create each animal and save its properties
      animal = self.animals.create(-1000, self.game.world.centerY, element.key, 0);

      //I'm saving everything that's not Phaser-related in an object
      animal.customParams = {text: element.text, sound: self.game.add.audio(element.audio)};

      //anchor point set to the center of the sprite
      animal.anchor.setTo(0.5);

      //create animal animation
      animal.animations.add('animate', [0, 1, 2, 1, 0, 1], 3, false);

      //enable input so we can touch it
      animal.inputEnabled = true;
      animal.input.pixelPerfectClick = true;
      animal.events.onInputDown.add(self.animateAnimal, this);
    });


Lastly, we want to play these sounds when the user touches an animal. This is, in our animateAnimal method:


//play animal animation and sound
  animateAnimal: function(sprite, event) {
    sprite.play('animate');
    sprite.customParams.sound.play();
  },


And now we have some nice sounds up and running!

Where did these sounds come from?

We grabbed a bunch of public domain animal sounds from Freesound.org and added the talking part (which we recorded) to them using Audacity. Freesound.org is a great site to find sound effects for your games. Always make sure you are respecting the corresponding licenses of the sound files you use. Some of them will require attribution or might not be allowed for commercial projects.

The text

The last part we have to add is the text labels of the animals. Below each animal we want to show the text label of the animal.

If you take a look at the code we have so far, you'll see the text of each animal has been present from the start in animalData and passed along to each sprite.

Let's create a method to show the text of an animal. This method will take an animal sprite as a parameter:


showText: function(animal) {
    //create the text object if it doesn't exist
    if(!this.animalText) {
      var style = {font: "bold 30pt Arial", fill: "#D0171B", align: "center"};
      this.animalText = this.game.add.text(this.game.width/2, this.game.height * 0.85, 'asdfasfd' , style);
      this.animalText.anchor.setTo(0.5);
    }

    this.animalText.setText(animal.customParams.text);
    this.animalText.visible = true;
  }


This shows the text of the animal that was passed as a parameter. To learn more about what properties you can pass to a text object make sure to check the Text documentation.

The first time we show an animal is in the create method. We also want to show its label. The part where we define our currentAnimal should look now like this:


//place first animal in the middle
    this.currentAnimal = this.animals.next();
    this.currentAnimal.position.set(this.game.world.centerX, this.game.world.centerY);
    this.showText(this.currentAnimal);


When we switch animals, we want to firstly hide the text while the transition takes place, which we can do with the visibility property of a sprite. Upon animation completion, we want to show the label of the new animal:


//switch animal
  switchAnimal: function(sprite, event) {

    //if an animation is taking place don't do anything
    if(this.isMoving) {
      return false;
    }

    this.isMoving = true;

    //hide text
    this.animalText.visible = false;

    var newAnimal, endX;
    //according to the arrow they pressed, which animal comes in
    if(sprite.customParams.direction > 0) {
      newAnimal = this.animals.next();
      newAnimal.x = -newAnimal.width/2;
      endX = 640 + this.currentAnimal.width/2;
    }
    else {
      newAnimal = this.animals.previous();
      newAnimal.x = 640 + newAnimal.width/2;
      endX = -this.currentAnimal.width/2;
    }

    //tween animations, moving on x
    var newAnimalMovement = game.add.tween(newAnimal);
    newAnimalMovement.to({ x: this.game.world.centerX }, 1000);
    newAnimalMovement.onComplete.add(function()
      {
        this.isMoving = false;

        //show text
        this.showText(newAnimal);
      }, this);
    newAnimalMovement.start();

    var currentAnimalMovement = game.add.tween(this.currentAnimal);
    currentAnimalMovement.to({ x: endX }, 1000);
    currentAnimalMovement.start();

    this.currentAnimal = newAnimal;
  },


Congrats! You have now a toddlers farming animals game. Feel free to modify further, add more animals and effects.

Tutorial source code and finished game

You can grab the tutorial source code and game assets in a ZIP file from here. If you want to see the finished product go here to see it live.

Exporting to native platforms

One of the great things about HTML5 games is that they can simply run on a web browser, no matter what device you are using. The web is a good way to distribute content, but if your target is the mobile audience you will be better off publishing on native app stores.

I'll quickly show you how you can make this web game into a native Android app using Cordova and the Intel XDK tool. For more detailed information on Cordova and hybrid apps check my previous tutorial at the HTML5 Hub How to Build a Virtual Pet Game with HTML5 and Cordova, where we also made use of native Cordova API.

If you've been using the Intel XDK you will already have a project created for this game, otherwise you can go to ProjectsNew Project, then Import an Existing HTML5 Project.

You should be able to run the game now under the Emulate tab. You can also preview it on our device using the options from the Test tab (you will have to install the App Preview app on your phone and sync your accounts).

In order to build for Android, as well as for other platforms, you need to go to the Build tab. For Android there are two options: plain Android or Crosswalk for Android. The difference between the two is that Crosswalk will install not just the game but its Chrome-based webview alongside, so that the game will look and behave the same no matter the phone's installed version of Android (only 4+ supported). That is the main advange. The down side is that the game APK file can become even 20 times heavier (example 1 MB for plain Android vs 20 MB for Crosswalk).

Regardless of the option you pick, the game will be built for Android in the cloud and you can install the resulting APK file on your phone or publish it to the Playstore and Amazon stores.

Have you made anything cool with the code of this game?

If you've crafted something cool with the code of this game, or you published a game after taking this tutorial, feel free to share it in the comments! If you publish a game by following any of my tutorials you can contact me and we'll feature it in the GameDev Academy to give you exposure and a few downloads.

Author Bio

Pablo Farias Navarro is a web + mobile developer and entrepreneur. Founder of Zenva (zenva.com), a startup that specializes in online teaching of programming and new technologies, having HTML5 as their main technology of choice.

For more complete information about compiler optimizations, see our Optimization Notice.

3 comments

Top
Alejandro Martin G.'s picture

hi, I made a little game and test on mi emolator and works good but when I build to apk, it doesnt work,could you help me or give me some tips.

I use to template game html5 with cordova.

this is my code.

app.js

(function () {
  
    var game = new Phaser.Game(480, 600, Phaser.AUTO, 'game');
    game.state.add('Game', BasicGame.Game);
    game.state.start('Game');

})();

Game.js

BasicGame = {

};
BasicGame.Game = function (game) {
   
};
BasicGame.Game.prototype = {

    init: function () {
        
        this.input.maxPointers = 1;
        this.stage.disableVisibilityChange = true;
        this.scale.scaleMode = Phaser.ScaleManager.SHOW_ALL;
        this.scale.pageAlignHorizontally = true;
        this.scale.pageAlignVertically = true;
        this.scale.forceOrientation(false, true);
        this.scale.setResizeCallback(this.gameResized, this);
        this.scale.updateLayout(true);
        this.scale.refresh();       
        this.physics.startSystem(Phaser.Physics.ARCADE);

    },

    preload: function () {
        this.load.image('logo', 'asset/phaser.png');

    },

    create: function () {
 
        this.logo = this.add.sprite(
            this.world.centerX,
            this.world.centerY,
            'logo');
    
        this.logo.anchor.setTo(0.5, 0.5);       

    },  

    gameResized: function (width, height) {    }

};

Md Sajjad Farooque R.'s picture

Hi,

Thanks for this awesome tutorial.

I just tried your tutorial. I made an android build with Intel XDK. I checked the CPU usage in my nexus 10. This small game is using 17% of CPU and 50 MB memory. Is there any way to reduce CPU usage or any tutorial?

Add a Comment

Have a technical question? Visit our forums. Have site or software product issues? Contact support.