Welcome to the first of a three-post series where I'll show you how to create a game using the Phaser.io JavaScript library.

This game will be similar to the old missile command game, but with a little twist. Instead of shooting missiles, we'll be shooting arrows to the falling parachuters to avoid them getting on our pyramids.

You can see in the next image how the game will look once completed:

Alt text

Looks fun, no? Let's start with the technology we'll be using to develop the game.

Phaser

Lately there has been an increasing number of JavaScript libraries to develop games, so why Phaser? Taken from the Phaser page, we have this list of features:

  • WebGL and Canvas support
  • Physics
  • Particles
  • Mobile browser support
  • ...other nice features

And one other thing I'm taking into consideration for choosing this library is the momentum it has, as you can see in the GitHub page of the project.

You can download the required Phaser files and also read the documentation in the Phaser website.

The project

The next step is to create the required files for the game. We will start by creating the index.html file.

index.html
<head>
    <title>Phaser Mayan Defense</title>
    <script src="lib/phaser.min.js"></script>
    <script src="src/boot.js"></script>
    <script src="src/preloader.js"></script>
    <script src="src/main_menu.js"></script>
    <script src="src/game.js"></script>"
</head>

This file is the starting point of our project. Here we include the files we need. In the first script line is the phaser library, and the other files are the different screens or states we'll be using in the game.

Basically, states can be seen as screens or scenes in your game. You can initialize the resources you will be using in that screen, do your render and update logic, and release the resources used in this screen.

  • In this game, the states we will use are the following:

  • Boot

  • Preloader
  • Main Menu
  • Game

We will review each of these files in detail. You can also find the link to download the source code and the resource files at the end of the post.

boot.js

The starting point for the game is the file boot.js. In this file we setup some settings for both desktop and mobile clients. Also in this file we can load resources (images) that we will use in the next game state (or screen).

In the init function we configure the different options for each type of device:

init: function() {
    // We don't need multi-touch support, so we specify 1 here
    this.input.maxPointers = 1;

    if (this.game.device.desktop) {
        // This section for desktop specific settings
        this.scale.pageAlignHorizontally = true;
    } else {
        // This section for mobile settings
        this.scale.scaleMode = Phaser.ScaleManager.SHOW_ALL;
        this.scale.setMinMax(480, 260, 1024, 768);
        this.scale.forceLandscape = true;
        this.scale.pageAlignHorizontally = true;
    }
},

We use the preload function to load all the resources for the next state:

preload: function() {
    this.load.image('preloaderBackground', 'res/images/preloader_background.png');
    this.load.image('preloaderBar', 'res/images/preloader_bar.png');
},

preloader.js

This file is where we can load all the required resources for the game. We can also set a background image and an animation that we want to show while the resources are being loaded.

In the preload function, we add the background and progress bar we preloaded in boot.js. We also use this function to load all the other resources we are going to use in the game.

preload: function () {
    this.background = this.add.sprite(0, 0, 'preloaderBackground');
    this.preloadBar = this.add.sprite(300, 400, 'preloaderBar');

    this.load.setPreloadSprite(this.preloadBar);

    this.load.image('titlepage', 'images/title.jpg');
    this.load.atlas('playButton', 'images/play_button.png', 'images/play_button.json');

    this.load.image('gameBackground', 'res/images/game_background.jpg');
}

As you can see in the code above, we are loading some images (jpg and png files), but we are also loading a json file. This json file contains the information about the atlas or spritesheet for the button. Basically an atlas is a group of images contained in a single texture. This way the loading of the resources could be optimized by the graphics processor.

To create the atlas I'm using this great software called TexturePacker. With TexturePacker I can create the images one by one using any image editing software and TexturePacker helps me create a single file from them. You can see below the single texture generated in TexturePacker. I will use this texture for the play button:

Alt text

This is an example of the json file generated by TexturePacker:

  {"frames": [

  {
    "filename": "play_button_click.png",
    "frame": {"x":2,"y":2,"w":252,"h":100},
    "rotated": false,
    "trimmed": true,
    "spriteSourceSize": {"x":6,"y":6,"w":252,"h":100},
    "sourceSize": {"w":270,"h":110},
    "pivot": {"x":0.5,"y":0.5}
  },

In our update function we only need to call the next step for now. Later we will add music to the game, so we could use the update function to wait for the music to be decoded to continue to the next state.

main_menu.js

This is the menu screen for our game. In this screen we will add a button to start playing, but you can also add buttons to see the high scores, to change settings and maybe to share your achievements in the game using social networks. But for now, we only need the Play button.

We use the create function to add the sprites and buttons for the main menu.

create: function () {
    this.add.sprite(0, 0, 'titlepage');
    this.playButton = this.add.button(400, 600, 'playButton', this.startGame, this, 'buttonOver', 'buttonOut', 'buttonOver');
},

In the code above, we are first adding first the background image. In the second line we are adding a button object. A button object is basically a sprite that can respond to certain type of events, more specifically pointer events:

  • Button events

  • Over: it's triggered when the pointer moves over the button.

  • Out: when the pointer that was previously over the Button moves out of it.
  • Down: when the pointer is pressed down on the button.
  • Up: when the pointer that was pressed down on the button is released again.

The next function is the event handler for the play button:

startGame: function (pointer) {
    this.state.start('Game');
}

In this event handler we only change the current state to the Game screen.

This is how our menu will look:

Alt text

game.js

The last state for our game is the Game state.

The properties listed below exist in every State in Phaser and they are automatically set for us. We can use them from any function inside the State.

MayanDefenseGame.Game = function (game) {
    this.game;      //  a reference to the currently running game (Phaser.Game)
    this.add;       //  used to add sprites, text, groups, etc (Phaser.GameObjectFactory)
    this.camera;    //  a reference to the game camera (Phaser.Camera)
    this.cache;     //  the game cache (Phaser.Cache)
    this.input;     //  the global input manager. You can access this.input.keyboard, this.input.mouse, as well from it. (Phaser.Input)
    this.load;      //  for preloading assets (Phaser.Loader)
    this.math;      //  lots of useful common math operations (Phaser.Math)
    this.sound;     //  the sound manager - add a sound, play one, set-up markers, etc (Phaser.SoundManager)
    this.stage;     //  the game stage (Phaser.Stage)
    this.time;      //  the clock (Phaser.Time)
    this.tweens;    //  the tween manager (Phaser.TweenManager)
    this.state;     //  the state manager (Phaser.StateManager)
    this.world;     //  the game world (Phaser.World)
    this.particles; //  the particle manager (Phaser.Particles)
    this.physics;   //  the physics manager (Phaser.Physics)
    this.rnd;       //  the repeatable random number generator (Phaser.RandomDataGenerator)
};

For now, the only useful function in the Game state will be the create function. Here we will add the game background image to the canvas:

create: function () {

    // Here we add the game background image
    this.add.sprite(0, 0, 'gameBackground');
},

Now we are ready to test the game. You could try to open the index.html file directly, or even better use a web server (like Apache) to host the code and run it. You can find below some notes about running the code in different web browsers.

  • Considerations to run the game

  • If you want to test the game using Chrome, you need to use a web server like Apache

  • You could use Firefox to test the game without a web server, because Firefox is less restrictive when loading files
  • You could use Glyph Designer to generate png and xml files for custom fonts

Final notes

So this is the first part of the tutorial. In the next step, I will add the basic functionality for the game, so stay tuned.

You can download or clone the code here.

I have more than 12 years of experience working with different technologies and platforms like Ruby on Rails, PHP, ASP.NET, Java, C++ and also some mobile development for Android, iOS and Windows Phone developing native apps and games. I love to be learning new things related to software development all the time, so I like to spend time learning and researching stuff. When I'm not developing software, I enjoy spending time with my family, playing some PC video games and watching movies.