Subscribe to GameFromScratch on YouTube Support GameFromScratch on Patreon
12. October 2014

 

The following is a guest tutorial written by Guntis at MightyEditor showing how you can easily use MightyEditor and Phaser to create a game.

 

 

This article will give you an example on how to use popular HTML5 game development framework Phaser and editor based on top of it - MightyEditor. This tutorial will take about an hour and only ~90 lines of actual code. Following game development aspects will be introduced: sprites, sprite animations, physics, collision, game states, player death/revival.

 

Requirements

 

You should use the newest version of Google Chrome. Other browsers should work, but are not tested.

 

Creating a project

 

In this tutorial we will create a coin collecting-spike avoiding platformer.

Go to http://mightyeditor.mightyfingers.com/ and click on "Create New Project". Enter the name of your game. In this tutorial, our game will be called "SockMan"

 

1

 

Next, locate the settings panel in the bottom-right and change the worldHeight, worldWidth, viewportHeight, and viewportWidth values to 1026x578, as shown in the image below. Viewport is the size of the in-game camera, but we won't be dealing with camera controls in this tutorial. 

 

2

 

Uploading game assets

 

Next up - game assets. First, download the assets and extract them. Then locate the asset manager in the upper-right corner and either select the Upload File/Upload Folder options or simply drag and drop the files from your file explorer straight to the manager panel.

 

3 

 

Creating the world

 

Select the stamp icon, then, in the asset panel, click on the image you want to place, bg_wall.png, for now and then click on the map grid to  place the asset on the map. Note, that the dark grey area represents the world/viewport. CTRL-click snaps the image to grid and you can move the image around afterwards by selecting the arrow tool in the left side menu. More accurate placement is possible by using the 'settings' menu in bottom-right. Next, place the 'grass_tile.png' asset like described above and you should you get a world like in the picture below.

 

4

 

Next up - grouping the placed objects together. Locate the objects panel in the middle-right and either select Add Group and then select and drag the objects in the newly created group or select the objects and then click on Group Selected Objects (SHIFT-click selects multiple objects). After that, rename the group to "bg" (double-click on group name) and your project should look like the image below.

 

 5

 

Note: it can be useful to lock (small lock icon on the right side) the background and any other groups/objects in place, so they become unclickable and don't mess with placing other objects.

 

Adding foreground objects

 

After placing background, we will add (almost) the rest of the objects to the game world - boxes, grass tiles, chest and spikes. To do that, simply use the stamp tool to place each object on the map (remember about CTRL to snap to grid) and group them accordingly - boxes and grass in "objects", spikes in "spikes" group and leave the chest 'groupless'. Everything should look similar to the image below, but feel free to create your own layout.

 

6

 

As for the actual character and coins, things get a little different, because there are multiple frames per image for animations. Select the character.png asset and in the Settings panel set its frameWidth and frameHeight values to 100px,the anchorX to 0.5 and anchorY values to 0.7.

 

7

After that just place the character sprite on the left side of the map by using the usual stamp tool. Repeat these step with the coin spritesheet, only changing the frameWidth to 113px and frameHeight to 71px. Both anchors are 0.5. Place multiple coins on the map and group them together in a 'coins' group. Finally, select the the text icon (big T) in the toolbar and place a "0" in the top right corner of your game world. In the objects panel, rename it to "gold". Now your game world should look like this and we can turn to actual coding.

 

8 

 

Switching to source editor

 

You can switch to the source editor in the top-left of the screen. Editor keyboard shortcuts can be found here.

 

9

 

Game states

 

Coding is done by using the Phaser development framework (homepage and documentation). There are different states (separate parts of the game like intro, menu, gameplay etc.). The MightyEditor gives you four states by default: boot, load, menu and play, but, in this tutorial, we will only be coding in the play state and without any menus, so we should just go straight to the play state. Switch to the 'menu.js' file and call the switch to the play state.

window.SockMan.state.menu = {
        create: function() {

            this.game.state.start("play");
        },

 

You can now click on the Open Game button in the top panel and the game will load... to a blank screen. The graphics must be initialized beforehand. To do that, we will switch to the play.js state. We need to use the mt.create function in the create method like this:

 

create: function() {
    this.bg = mt.create("bg");
    this.character = mt.create("character");
    this.spikes = mt.create("spikes");
    this.chest = mt.create("chest");
    this.objects = mt.create("objects");
    this.coins = mt.create("coins");
    this.gold = mt.create("gold");
},

 

This initializes and creates the game sprites and sprite groups. Now, when opening the game, the visuals will be there, but the image is static.

 

Adding Physics

 

To add movement, first we must enable physics on the character. To do that, head back to the Map Editor and select your character sprite. In the bottom-right, use the Physics panel to enable it. Set these values:

  • enable: 1
  • immovable: 0
  • size-width: 40
  • size-height: 70
  • gravity-allow: 1
  • gravity-y:1000
  • collideWorldBounds: 1

 

10

 

In the end, everything should look like this:  Note: the size parameters are for the physics body, so the game interacts only with the area you want, not the blank parts or the sprite. Your character should now fall through the floor and stay on the edge of the game (that's what collideWorldBounds is for). To fix that, we must enable collision for the objects group.  To do that, just change the physics enable parameter of the group and add this piece of code in your update method (a function, looped 60 times per second):

 

this.game.physics.arcade.collide(this.character, this.objects.self, function(character, object) {
            console.log('Collision detected');
        }, null, this);

And all should be well. The collision detection's first two arguments check for interaction between two entities - the character sprite and a group of objects - and the third argument is a function which does something when these two objects (the character and a separate object of the group) do collide. Congratulations! Your character no longer falls through the floor tiles (grass/boxes).

 

Movement

 

But we need to move. To do that, the keyboard controls must be enabled beforehand. Simply put these two lines in the create method:

 

this.cursors = this.game.input.keyboard.createCursorKeys();
this.space = this.game.input.keyboard.addKey(Phaser.Keyboard.SPACEBAR);

 

The keyboard.createCursorKeys() method initializes the arrow keys. Other keys, like SPACEBAR, SHIFT or CTRL must be initialized like shown above. After that, define actions to do when a key is pressed in the update method:

 

if (this.cursors.left.isDown) {
    this.character.body.velocity.x = -200;
} else if (this.cursors.right.isDown) {
    this.character.body.velocity.x = 200;
} else {
    this.character.body.velocity.x = 0;
}
if (this.space.isDown || this.cursors.up.isDown) {
    this.character.body.velocity.y = -550;
}

 

Arrow keys control your character, alternatively you can jump with SPACEBAR. Or maybe we should say - fly! But we only want to jump, not fly. To do that, one must enable the character to jump only if it is standing on the ground. Delete the current piece of jump code (the one with space and cursors.up) and instead place this in your collision detection function, so it looks like this:

 

this.game.physics.arcade.collide(this.character, this.objects.self, function(character, object) {
    if (this.space.isDown || this.cursors.up.isDown) {
        if (object.body.touching.up) {
            this.character.body.velocity.y = -550;
        }
    }

}, null, this);

 

Adding Character Animations

 

Animations, just like mostly everything, must first be initialized. In the create method, add these lines of code:

this.character.animations.add('stand', [0, 1, 2, 3], 10, true);
this.character.animations.add('run', [6, 7, 8, 9, 10, 11], 10, true);
this.character.animations.add('jump', [12, 13], 10, false);
this.character.animations.add('die', [18, 19], 10, false);
this.character.animations.play('stand');

 

These lines describe animations for your character. The first argument is the 'key' of the animation, the second - an array of frames which this particular animation uses, the third - frames per second and the last argument describes whether the animation should loop. The last line starts an animation when you launch the game. The rest of the animations is played according to situation, when certain condition is met, like a button press. The rest is added in the update method like this:

 

if (this.cursors.left.isDown) {
    this.character.body.velocity.x = -200;
    this.character.animations.play('run');
    this.character.scale.x = -1;
} else if (this.cursors.right.isDown) {
    this.character.body.velocity.x = 200;
    this.character.animations.play('run');
    this.character.scale.x = 1;
} else {
    this.character.body.velocity.x = 0;
    this.character.animations.play('stand');
}

 

And for jump animation, update your collision detection function with this:

 

this.game.physics.arcade.collide(this.character, this.objects.self, function(character, object) {
    if (this.space.isDown || this.cursors.up.isDown) {
        if (object.body.touching.up) {
            this.character.animations.play('jump');
            this.character.body.velocity.y = -550;
        }

    }
}, null, this);

 

At this point you might be wondering why you can't see a jump animation. It's because it gets overwritten by the 'run' or 'stand' animations since their conditions are met as well. We must invent another variable which tells the animations whether the character is in the air. Long story short, after putting this variable in, all of the update method will look like this:

 

update: function() {
    var standing = false;
    this.game.physics.arcade.collide(this.character, this.objects.self, function(character, object) {
        if (object.body.touching.up) {
            standing = true;
        } else standing = false;
        if (this.space.isDown || this.cursors.up.isDown) {
            if (object.body.touching.up) {
                this.character.animations.play('jump');
                this.character.body.velocity.y = -550;
                standing = false;
            }

        }
    }, null, this);

    if (this.cursors.left.isDown) {
        this.character.body.velocity.x = -200;
        if (standing) this.character.animations.play('run');
        this.character.scale.x = -1;
    } else if (this.cursors.right.isDown) {
        this.character.body.velocity.x = 200;
        if (standing) this.character.animations.play('run');
        this.character.scale.x = 1;
    } else {
        this.character.body.velocity.x = 0;
        if (standing) this.character.animations.play('stand');
    }
}

 

Collecting Coins

 

Before you are able to collect coins, their physics must be enabled, the physics body size set to 24x24 and offsetY to 10.

 

 

Next, we initialize the animation:

 

this.coins.self.callAll('animations.add', 'animations', 'collect', [7, 8], 10, false);

 

Note the difference between this line and those used to initialize the character's animations. Since the character was a lone sprite but the coins are all in a group, we must use the callAll method which initializes the animation for each and every child of the group separately. The first argument of the method is the method you would normally use, the second is the context and the rest is identical to adding animations as usual. After animating, we determine overlapping between the character and coins, making the coin disappear  when touch ends and the animation is done playing, and adding +1 to the counter in the upper-right corner:

 

this.game.physics.arcade.overlap(this.character, this.coins.self, function(character, coin) {
    coin.body = null;
    var coinCollect = coin.animations.play('collect');
    coinCollect.killOnComplete = true;
    var newPoints = parseInt(this.gold._text) + 1;
    this.gold.setText(newPoints);
}, null, this);

 

The coin.body is set to null, disabling the physics body. Otherwise the points would be added as long as the animation is still playing. since the character overlaps the animation.

 

Spikes, Life and Death

 

Next up is being able to kill the character when it touches the spikes. To do this, you must enable the physics of your 'spikes' group and set the body height to 20px and the offsetY parameter to 44px - this changes the Y coordinate from which the body is calculated. Pretty much an alternative to anchorY. After that comes the now usual collision detection:

 

this.game.physics.arcade.collide(this.character, this.spikes.self, function(character, spike) {
    if (character.alive) character.animations.play('die');
    character.body.velocity.x = 0;
    character.body.velocity.y = 0;
    character.alive = false;
}, null, this); 

 

The only problem now is that, after dying, you can still move. To avoid this, check if the character.alive is true before movement:

 

var standing = false;
this.game.physics.arcade.collide(this.character, this.objects.self, function(character, object) {
    if (object.body.touching.up) {
        standing = true;
    } else standing = false;
    if ((this.space.isDown || this.cursors.up.isDown) && character.alive) {
        if (object.body.touching.up) {
            this.character.animations.play('jump');
            this.character.body.velocity.y = -550;
            standing = false;
        }

    }
}, null, this);
if (this.character.alive) {
    if (this.cursors.left.isDown) {
        this.character.body.velocity.x = -200;
        if (standing) this.character.animations.play('run');
        this.character.scale.x = -1;
    } else if (this.cursors.right.isDown) {
        this.character.body.velocity.x = 200;
        if (standing) this.character.animations.play('run');
        this.character.scale.x = 1;
    } else {
        this.character.body.velocity.x = 0;
        if (standing) this.character.animations.play('stand');
    }
}

 

And finally, we add the ability to revive and send your character to start position by pressing SPACEBAR (set the character coordinates to your starting coordinates, viewed in the Map Editor):

 

if (this.space.isDown && !this.character.alive) {
    this.character.revive();
    this.character.x = 68;
    this.character.y = 452;
}

 

Achieving the Goal

 

One last thing - making the game do something when touching the big chest. This time we won't be using physics but check for overlapping differently (viable for single sprites only, not groups). First, add this checkOverlap function after the update method (don't forget to add a coma after the ending brace of the update method):

 

checkOverlap: function(spriteA, spriteB) {
    var boundsA = spriteA.getBounds();
    var boundsB = spriteB.getBounds();
    return Phaser.Rectangle.intersects(boundsA, boundsB);
}

 

And finally - call this function from within update:

 

if (this.checkOverlap(this.character, this.chest)) {
    this.game.state.start("play");
}

 

In this case, the 'play' state is restarted as soon as you touch the chest.

 

Congratulations!

 

Your game is now be fully playable and the code should closely resemble this:

 

"use strict";
window.SockMan.state.play = {
    create: function() {
        this.bg = mt.create("bg");
        this.character = mt.create("character");
        this.spikes = mt.create("spikes");
        this.chest = mt.create("chest");
        this.objects = mt.create("objects");
        this.coins = mt.create("coins");
        this.gold = mt.create("gold");

        this.cursors = this.game.input.keyboard.createCursorKeys();
        this.space = this.game.input.keyboard.addKey(Phaser.Keyboard.SPACEBAR);

        this.character.animations.add('stand', [0, 1, 2, 3], 10, true);
        this.character.animations.add('run', [6, 7, 8, 9, 10, 11], 10, true);
        this.character.animations.add('jump', [12, 13], 10, false);
        this.character.animations.add('die', [18, 19], 10, false);
        this.character.animations.play('stand');
        this.coins.self.callAll('animations.add', 'animations', 'collect', [7, 8], 10, false);
    },

    update: function() {
        var standing = false;
        this.game.physics.arcade.collide(this.character, this.objects.self, function(character, object) {
            if (object.body.touching.up) {
                standing = true;
            } else standing = false;
            if ((this.space.isDown || this.cursors.up.isDown) && character.alive) {
                if (object.body.touching.up) {
                    this.character.animations.play('jump');
                    this.character.body.velocity.y = -550;
                    standing = false;
                }
            }
        }, null, this);
        if (this.character.alive) {
            if (this.cursors.left.isDown) {
                this.character.body.velocity.x = -200;
                if (standing) this.character.animations.play('run');
                this.character.scale.x = -1;
            } else if (this.cursors.right.isDown) {
                this.character.body.velocity.x = 200;
                if (standing) this.character.animations.play('run');
                this.character.scale.x = 1;
            } else {
                this.character.body.velocity.x = 0;
                if (standing) this.character.animations.play('stand');
            }
        }

        this.game.physics.arcade.overlap(this.character, this.coins.self, function(character, coin) {
            coin.body = null;
            var coinCollect = coin.animations.play('collect');
            coinCollect.killOnComplete = true;
            var newPoints = parseInt(this.gold._text) + 1;
            this.gold.setText(newPoints);
        }, null, this);

        this.game.physics.arcade.collide(this.character, this.spikes.self, function(character, spike) {
            if (character.alive) character.animations.play('die');
            character.body.velocity.x = 0;
            character.body.velocity.y = 0;
            character.alive = false;
        }, null, this);

        if (this.space.isDown && !this.character.alive) {
            this.character.revive();
            this.character.x = 68;
            this.character.y = 452;
        }

        if (this.checkOverlap(this.character, this.chest)) {
            this.game.state.start("play");
        }
    },

    checkOverlap: function(spriteA, spriteB) {
        var boundsA = spriteA.getBounds();
        var boundsB = spriteB.getBounds();
        return Phaser.Rectangle.intersects(boundsA, boundsB);
    }
};

 

Full game project: http://mightyeditor.mightyfingers.com/#pe45-copy

Final game: http://mightyeditor.mightyfingers.com/data/projects/pe45/phaser/index.html

The end result:

 

Click here to open in a new window.

Programming


23. September 2014

 

 

In the previous particle tutorial I used something called a tween followed by the instructions “don’t worry about it, I will cover them later”.  Well, welcome to later!

 

First off, what exactly is a tween?  It’s actually probably exactly what you expect it is, basically it’s “between” turned into a verb.  Tweens are all about transitioning from one state to another, and they are incredibly handy.  Let’s just straight in with an example:

 

/// <reference path="phaser.d.ts"/>
class SimpleGame {
    game: Phaser.Game;
    sprite: Phaser.Sprite;
    
    constructor() {
        this.game = new Phaser.Game(640, 480, Phaser.AUTO, 'content', {
            create: this.create, preload:
            this.preload, render: this.render
        });
    }
    preload() {
        this.game.load.image("decepticon", "decepticon.png");
        
    }
    render() {
    }
    create() {
        this.sprite = this.game.add.sprite(0, 0, "decepticon");
        this.game.add.tween(this.sprite).to(
            { x: 400 }, 5000, Phaser.Easing.Linear.None, true, 0, Number.MAX_VALUE, true);
    }
}

window.onload = () => {
    var game = new SimpleGame();
};

 

This example shows a to() tween, which is it tweens between the initial value and the value you specify.  When creating a tween, you pass in the option you wish to tween, in this case a Phaser.Sprite.  The first value are the properties we wish to tween, in this cases sprite’s x value.  Next we tell it how long to take ( 5 seconds ), then pass in the easing function we want to use, in this case none ( which by the way, would have been the default value ), next is the delay before beginning ( right away ), how many times to perform ( infinite ) the tween, then finally we pass true to bounce.  Bounce says after you are done the tween, go back to the beginning.

 

And here is the result

 

 

As you can see the image moves across the screen until it’s x value is 400.

 

Now let’s take a look at how the easing function affects the tween.  Instead of no easing function, let’s apply an elastic band type affect.  We use InOut, which means it will ease at the beginning and end of the Tween.

 

    create() {
        this.sprite = this.game.add.sprite(0, 0, "decepticon");
        this.game.add.tween(this.sprite).to({ x: 400 }, 5000,
            Phaser.Easing.Elastic.InOut, true, 0, Number.MAX_VALUE, true);
    }

 

And the result:

 

 

Tweens don't have to be limited to positioning items either, you can tween just about any value. For example, let’s instead tween the alpha value of our sprite:

 

    create() {
        this.sprite = this.game.add.sprite(0, 0, "decepticon");
        this.game.add.tween(this.sprite).to({alpha:0 }, 5000,
            Phaser.Easing.Quadratic.In, true, 0, Number.MAX_VALUE, true);
    }

 

And the result

 

 

You can also chain together tweens to perform a series of transitions:

 

    create() {
        this.sprite = this.game.add.sprite(0, 0, "decepticon");
        this.game.add.tween(this.sprite)
            .to({ x: 400 }, 2000)
            .to({ y: 250 }, 2000)
            .to({ x: 0 }, 2000)
            .to({ y: 0 }, 2000).loop().start();
    }

 

Resulting in:

 

 

Tweens also have event handlers attached. Here for example is a tween that has an onStart and onComplete event handler, that fire before and after the tween completes respectively.

 

    create() {
        this.sprite = this.game.add.sprite(0, 0, "decepticon");
        var tween = this.game.add.tween(this.sprite);
        tween.to({ x: 400 });

        tween.onStart.addOnce(() => {
            this.sprite.scale.setMagnitude(0.5);
        });
        tween.onComplete.addOnce(() => {
            this.game.add.tween(this.sprite).to({ x: 0 }).start();
            },this);
        tween.start();
    }

 

Tweens provide a pretty powerful but simple way of adding actions, either in sequence or parallel, to your game’s contents.

 

Programming


12. September 2014

 

 

Apparently on September the 9th Phaser 2.1 was released  followed quickly by the ohhhh oops Phaser 2.1.1 hotfix release.  It is important to note that this releasePhaser Logo has some code breaking changes in it, so read carefully before upgrading to see how your code might be impacted!

 

 

The release notes:

 

Version 2.1.1. of Phaser is an emergency point release. It addresses a potential race condition that could happen in States that tried to change state from the create method but had an empty preloader or pre-cached assets.

The list of changes below are from 2.1.0 - 9th September 2014

 
New Features
  • Updated to p2.js 0.6.0 - this was an API breaking change, so please see the p2.js section of this change log specifically if you're using p2 in your game.
  • If you are using CocoonJS, please set your game render type to CANVAS and not WEBGL or AUTO. You should also disable any of the ScaleManager screen resizing or margin setting code. By default in this mode CocoonJS will now set 'screencanvas=true' which helps with performance significantly.
  • Ninja Physics is no longer included in the build files by default. Not enough people were using it, and not enough contributions were coming in to help polish it up, so we've saved the space and removed it. It's still available in the grunt build files if you require it, but we're deprecating it from the core library at this time. It will make a return in Phaser3 when we move to a modular class system.
  • ScaleManager has a new scaleMode called RESIZE which will tell Phaser to track the size of the parent container (either a dom element or the browser window if none given) and set the canvas size to match it. If the parent changes size the canvas will resize as well, keeping a 1:1 pixel ratio. There is also a new ScaleManager.setResizeCallback method which will let you define your own function to handle resize events from the game, such as re-positioning sprites for a fluid responsive layout (#642)
  • The width and height given to the Phaser.Game constructor can now be numbers or strings in which case the value is treated as a percentage. For example a value of "100%" for the width and height will tell Phaser to size the game to match the parent container dimensions exactly (or the browser window if no parent is given). Equally a size of "50%" would tell it to be half the size of the parent. The values are retained even through resize events, allowing it to maintain a percentage size based on the parent even as it updates.
  • Device will now detect for Kindle and PS Vita (thanks @lucbloom)
  • Device will now detect for Cordova (thanks @videlais #1102)
  • Arcade Physics Body.skipQuadTree is a new boolean that if set to true when you collide the Sprite against a Group it will tell Phaser to skip using a QuadTree for that collision. This is handy if this Body is especially large.
  • Arcade Physics World.skipQuadTree will disable the use of all QuadTrees in collision methods, which can help performance in tightly packed scenes.
  • Cordova 'deviceready' event check added (thanks @videlais #1120)
  • Loader.useXDomainRequest boolean added. If true (the default is false, unless the browser is detected as being IE9 specifically) it will use XDomainRequest when loading JSON files instead of xhr. In rare IE edge-cases this may be required. You'll know if you need it (#1131 #1116)
  • Added support for Tiled objects type field (thanks @rex64 #1111)
  • Tile properties are now copied from the Tiled JSON data to the Phaser.Tile objects when parsed (thanks @beeglebug #1126)
  • All Images now have a frameData value, even if it's only one frame. This removes lots of engine code needed to check if images are sprite sheets or not, and simplifies game code too (thanks @lucbloom #1059)
  • Added a new Phaser.Rope object. This allows for a series of 'chained' Sprites and extends the Rope support built into Pixi. Access it via game.add.rope (thanks @codevinsky #1030)
  • Phaser.Device.isAndroidStockBrowser will inform you if your game is running in a stock Android browser (rather than Chrome) where you may wish to scale down effects, disable WebGL, etc (thanks @lucbloom #989)
  • Phaser.Camera has a new property position which is a Point object that allows you to get or set the camera position without having to read both the x and y values (thanks @Zielak#1015)
  • TileSprite now has the alive property, which should help with some Group operations (thanks @jonkelling #1085)
  • Events.onDestroy is a new signal that is dispatched whenever the parent is being destroyed. It's dispatched at the start of the destroy process, allowing you to perform any additional house cleaning needed (thanks @jonkelling #1084)
  • Group.onDestroy is a new signal that is dispatched whenever the Group is being destroyed. It's dispatched at the start of the destroy process, allowing you to perform any additional house cleaning needed (thanks @jonkelling #1084)
  • ScaleManager.destroy now removes the window and document event listeners, which are no longer created anonymously (thanks @eguneys #1092)
  • Input.Gamepad.destroy now destroys all connected SinglePads and clears event listeners.
  • SinglePad.destroy now clears all associated GamepadButton objects and signals.
  • Device.node and Device.nodeWebKit are two new properties (thanks @videlais #1129)
  • P2.PointProxy.mx and my values are get and set in meters with no pixel conversion taking place.
  • P2.InversePointProxy.mx and my values are get and set in meters with no pixel conversion taking place.
  • Pointer.dirty is a new boolean that is set by the InputHandler. It tells the Pointer to re-check all interactive objects it may be over on the next update, regardless if it has moved position or not. This helps solve issues where you may have a Button that on click generates a pop-up window that now obscures the Button (thanks @jflowers45 #882)
  • SoundManager.destroy is a new method that will destroy all current sounds and reset any callbacks.
  • StateManager.clearCurrentState now handles the process of clearing down the current state and is now called if the Game is destroyed.
  • Game.destroy now clears the current state, activating its shutdown callback if it had one. It also now destroys the SoundManager, stopping any currently running sounds (#1092)
  • Animation.onUpdate is a new event that is dispatched each time the animation frame changes. Due to its intensive nature it is disabled by default. Enable it withAnimation.enableUpdate = true (#902)
  • Device now has new features to support detection of running inside a CocoonJS.App (thanks@videlais #1150)
  • Support for CocoonJS.App's 'onSuspended' and 'onActivated' events, making it so that the timers and sounds are stopped/started and muted/unmuted when the user swaps an app from the background to the fore or the reverse (thanks @videlais #1152)
  • Canvas.removeFromDOM(canvas) will remove a canvas element from the DOM.
  • Game.destroy now removes the games canvas element from the DOM.
  • ScaleManager.setMinMax(minWidth, minHeight, maxWidth, maxHeight) is a handy function to allow you to set all the min/max dimensions in one call.
  • ArcadePhysics.collide and overlap can now accept 2 Arrays of objects to be used in the collision checks (thanks @ctmartinez1992 #1158)
  • RetroFont has a new property called frameData which contains the Frame objects for each of the letters in the font, which can be used by Sprites.
  • Phaser.Canvas.setImageRenderingCrisp now sets image-rendering: pixelated, perfect for pixel art, which is now supported in Chrome 38.
  • Phaser.Mouse will now add a listener to the window to detect mouseup events. This is used to detect if the player releases the mouse while outside of the game canvas. Previously Pointer objects incorrectly thought they were still pressed when you returned the mouse over the canvas (#1167)
  • Rectangle.centerOn(x,y) allows you to quickly center a Rectangle on the given coordinates.
  • Group.addMultiple allows you to pass an array of game objects and they'll all be added to the Group in turn.
  • The StateManager will now check if a State has a method called resize. If it does, and if the game is running in the RESIZE Scale Mode then this method will be called whenever the game resizes. It will be passed two parameters: width and height that will match the games new dimensions. Resizing can happen as a result of either the parent container changing shape, or the browser window resizing.
  • Rectangle.topRight returns a Point object that represents the top-right coordinate of the Rectangle.
  • The grunt script now builds a new version of Phaser without any physics (including Arcade Physics), Tilemaps or Particles. This build is called phaser-no-physics.js and works stand-alone. Please note that things like the GameObjectFactory aren't changed, so they will still try and create a Tilemap for example should you ask them to (thanks @eguneys #1172)
  • Camera.roundPx is a new boolean. If set to true it will call view.floor as part of its update loop, keeping its boundary to integer values. Set to false to disable this from happening (#1141)
  • Phaser.Easing.Default is a new property that is used when a specific type of ease isn't given. It defaults to Linear.None but can be overridden to anything (thanks @alvinsight)
 
Updates
  • TypeScript definition updates to help fix for the noimplicitany option (thanks @Waog#1088)
  • TypeScript definitions fixes and updates (thanks @clark-stevenson @englercj @saikobeeand @rhmoller)
  • All of the Pixi geom classes have been removed from the build file as they aren't needed (the Phaser.Geom classes overwrite them), saving some space in the process.
  • Improved consistency of clone methods on geometry classes (thanks @beeglebug #1130)
  • Removed Cache.isSpriteSheet method as no longer required (see #1059)
  • Added Cache.getFrameCount to return the number of frames in a FrameData.
  • Input.setMoveCallback has been removed due to deprecation.
  • BitmapData.refreshBuffer has been removed and replaced with BitmapData.update.
  • BitmapData.drawSprite has been removed due to deprecation. Use BitmapData.draw instead.
  • Pointer.moveCallback has been removed due to deprecation.
  • SinglePad.addButton has been removed due to deprecation.
  • P2.Body.loadData has been removed due to deprecation.
  • P2.World.defaultFriction and defaultRestitution have been removed due to deprecation.
  • Canvas.create noCocoon parameter has been removed due to deprecation.
  • Color.getColorInfo, RGBtoHexstring, RGBtoWebstring and colorToHexstring has been removed due to deprecation.
  • P2.PointProxy.x and y values are now returned in pixels (previously they were returned in meters). See PointProxy.mx/my for meter values.
  • P2.InversePointProxy.x and y values are now returned in pixels (previously they were returned in meters). See PointProxy.mx/my for meter values.
  • Arcade.overlap and collide are now more consistent about allowing a Group vs. Group or Group vs. Array of Groups set (thanks @pyromanfo #877 #1147)
  • The Pointer move callbacks are now sent an extra parameter: fromClick allowing your callbacks to distinguish between the Pointer just moving, or moving as a result of being pressed down (thanks @iforce2d #1055)
  • GamePad and SinglePad onAxisCallback parameters have changed. You are now sent: this (a reference to the SinglePad that caused the callback), the axis index and the axis value in that order.
  • If Time.elapsed was > Time.timeCap it would reset the elapsed value to be 1 / 60. It's now set to Time.timeCap and Time.timeCap defaults to 1 / 60 * 1000 as it's a ms value (thanks@casensiom #899)
  • Tiled polylines are now imported into the map objects property as well as map collision (#1117)
  • Tile.setCollision now adjusts the tiles interesting faces list as well, this allows you to create one-way jump tiles without using custom callbacks on a specific tile basis (thanks@RafaelOliveira #886)
  • Stage.offset has been moved to ScaleManager.offset
  • Stage.bounds has been removed, you can access it via Stage.getBounds.
  • Stage.checkOffsetInterval has been moved to ScaleManager.trackParentInterval
  • ScaleManager.hasResized signal has been removed. Use ScaleManager.setResizeCallback instead.
  • The World bounds can now be set to any size, including smaller than the game dimensions. Before it was locked to a minimum size of the game canvas, but it can now be anything.
  • ScaleManager.orientationSprite has been removed because it never displayed correctly anyway (it would be distorted by the game scale), it will be bought back in a future version by way of a custom orientation state.
  • ArcadePhysics.overlap has been updated so that the Body.overlapX/Y properties are set to the amount the two bodies overlapped by. Previously they were zero and only populated during the separation phase, but now the data is available for just overlap checks as well. You can then use these values in your ovrelap callback as required - note that they are changed for every check, so a Sprite overlap tested against 10 other sprites will have the overlapX/Y values updated 10 times in a single collision pass, so you can only safely use the values in the callback (#641)
  • Cache.getImage now returns null if the requested image wasn't found.
  • BitmapData now returns a reference to itself from all of its drawing related methods, allowing for easy function chaining.
  • The default size of a BitmapData if no width/height is given has been changed from 100x100 to 256x256.
  • Phaser.Text.destroy will now destroy the base texture by default (#1162)
  • BitmapData.copyPixels is now called BitmapData.copyRect and the method signature has changed.
  • BitmapData.draw method signature has changed significantly.
  • Phaser.Canvas.getSmoothingEnabled will return true if the given context has image smoothing enabled, otherwise false.
  • Math.numberArrayStep is a new method that allows you to return an array of numbers frommin to max including an optional step parameter (thanks @codevinsky #1170)
  • Removed redundant if check from StateManager.preUpdate (thanks @FedeOmoto #1173)
 
Bug Fixes
  • Remove escaping backslashes from RetroFont text set documentation (thanks @jackrugile#1051)
  • Phaser.Loader was incorrectly getting the responseText from _xhr instead of _ajax on IE9 xDomainRequests (thanks @lardratboy #1050)
  • Phaser.Physics.P2.addPolygon now takes a nested array again (thanks @wayfu #1060)
  • Fix for previous PR #1028 where the P2.setBoundsToWorld call was overriding setBoundsToWorld in the P2 constructor (thanks @Dumtard #1028)
  • Fix for scale issues in CocoonJS using webgl renderer and screencanvas (thanks@txusinho #1064)
  • Resolves issue with pixel perfect click / over detection on Sprites that used trimmed image atlases for animations or frames > 0.
  • Group.swap() updates the Z index values properly (thanks @Blank101 #1090)
  • Device now recognises ChromeOS as a desktop (thanks @alvinsight @hilts-vaughan#1091)
  • Fixed Point.rotate bug (thanks @gamedolphin #1107)
  • InputHandler.checkBoundsRect was incorrectly assigning a property in Sprites fixed to the camera being dragged left (thanks @CraigBeswetherick #1093)
  • Swapped argument order of Rectangle.containsRect (thanks @beeglebug #1095 #1125)
  • The Game configuration object "renderer" property was being wrongly assigned to Game.renderer instead of renderType (thanks @FedeOmoto #1127)
  • Fixed Group.removeBetweens default endIndex (thanks @darfux #1142)
  • Debug.cameraInfo no longer crashes if the camera bounds are nulled (thanks @wayfu#1143)
  • Camera.setBoundsToWorld no longer crashes if the camera bounds are nulled (thanks@wayfu #1143)
  • Fixed the resolution uniform type in the SampleFilter (thanks @VictoryRice #1137)
  • Calling P2.Body.destroy or ArcadePhysics.Body.destroy wouldn't null the parent sprite body, causing it to error in the next update (thanks @jonathanhooker #1077)
  • BitmapFonts are now correctly added to the Cache._bitmapFont array and returned via Cache.getBitmapFont (thanks @prudolfs #1076)
  • InputHandler docs updated to avoid Pointer data-type confusion (#1097)
  • If you used a single Game configuration object and didn't specify the enableDebug property it would crash on Debug.preUpdate (thanks @luizbills #1053)
  • The P2.World.postBroadphaseHandler now checks if the returned pairs array is empty or not before processing it (thanks @wayfu #934)
  • Tilemap.hasTile now checks the Tile.index value and will return false if the index is -1 (i.e. a non-active tile) (thanks @elgansayer #859)
  • Sound.restart used to cause the Sound to double-up if it was already playing when called. Now correctly stops the sound before restarting it (thanks @wombatbuddy #1136)
  • GamePad axis detection now works again properly in Firefox (#1035)
  • GamepadButton.justPressed and justReleased now correctly report if the button has just been pressed or released (thanks @padpadpad #1019)
  • TilemapParser.getEmptyData now correct adds an empty bodies array into layers. This fixes an issue where p2 couldn't convert a csv map into collision tiles (thanks @sru #845)
  • CocoonJS doesn't support mouse wheel events so they've been moved into a conditional check (thanks @videlais #1151)
  • ScaleManager window.resize handler would constantly dispatch enterPortrait and enterLandscape events on window resizing, regardless if it actually entered that orientation or not.
  • Added Sound._muteVolume which stops Firefox and IE9 crashing if you try to unmute a sound that hasn't yet been muted, which can also happen as a result of a game visibility change (thanks @osmanzeki #1108 #1123)
  • P2.World.getSprings used to return an empty array, but now returns all the Springs in the world (#1134)
  • Tween.generateData would skip the end values in the data array. They are now included as the object in the final array element.
  • Rectangle.bottom setter swapped the order of the calculation (thanks @JakeCoxon #1165)
  • Phaser.Text wouldn't render the text to its local canvas if you passed the text on the constructor and didn't add it to the display list. If a string is given it now updates the local canvas on creation.
  • Signal.removeAll would ignore the context parameter and remove all bindings regardless (thanks @alect #1168)
  • P2.Body.addCapsule didn't use to pass the radius value through pxm, but now does so you have to specify it in pixels, not meters.
 
p2.js 0.6.0 Changes and New Features
  • DistanceConstraint signature changed to take the new localAnchors.
  • World.createDistanceConstraint signature changed to include new local anchors (thanks@rhmoller #1169)
  • RevoluteConstraint signature changed to include worldPivot.
  • P2.Body now uses the new Body.type value instead of Body.motionState, however as P2.Body already have a property called type we have left the motionState getter/setter in for now.
  • World.enableBodySleeping has been removed and replaced with World.sleepMode.
  • Phaser P2.Springs are now LinearSprings by default.
  • World.createRotationalSpring will now let you create rotational springs.
 
Breaking changes
  • Renamed property .motionState to .type in class Body.
  • Changed constructor of RevoluteConstraint. Now the local pivots are passed as options instead of direct arguments. See the constraints demo.
  • Removed World.prototype.toJSON and .fromJSON.
  • Removed properties .enableBodySleeping and .enableIslandSleeping from World instances. The enum .sleepMode can be used instead. See the sleep demo.
  • Converted Spring to a base class for the new LinearSpring and RotationalSpring classes. LinearSpring can be used as the old Spring.
  • Utils.ARRAY_TYPE can now be overridden by injecting a global called P2_ARRAY_TYPE. Support for GLMAT_ARRAY_TYPE has been removed.
 
Other changes
  • Added flag .enableFrictionReduction to Narrowphase.
  • Added RevoluteConstraint.prototype.setLimits.
  • Added PrismaticConstraint.prototype.setLimits.
  • LockConstraint, DistanceConstraint, and GearConstraint can now be constructed from current body transforms.
  • RevoluteConstraint can now be constructed from the current body transforms and a world point.
  • Material id can now be passed via constructor.
  • ContactMaterial instances now have a property .contactSkinSize.
  • Added method Body.prototype.getAABB.
  • Limits for DistanceConstraint. See the DistanceConstraint demo.
  • Added Body.prototype.overlaps.
  • Added class OverlapKeeper.
  • If substepping is used in World.prototype.step, the substeps are aborted if slower than real time.
  • Added Heightfield/Convex and Heightfield/Circle collision support.
  • Added property .overlapKeeper to World.
  • EventEmitter.prototype.has can now check if any listeners were added to a given topic.
  • Added Utils.defaults.

 

In reading through the changes, I do not believe any of the GameFromScratch Phaser tutorial series will be impacted if you use the newest version.

News


12. September 2014

 

 

In my previous Phaser tutorial on particles I used a sprite sheet to provide particles in one of the examples, then realized I hadn’t covered how to actually use a sprite sheet yet, oops!  So this tutorial is going to correct that oversight.  A spritesheet ( also known as a texture atlas ), is simply a collection of images together in a single image file.  Loading a single file into memory is often more efficient than loading dozens on small images.  It’s also generally easier from a resource management perspective.

 

Let’s take a look using the texture I used for the particle example.  It’s a seamless animation of a robin in flight that I downloaded from here.  Here is a small version of the image:

robin-782x1024

 

Now imagine the above image as a 5x5 grid of images.  This gives 22 240x314 bird images and 3 empty spaces.  Now let’s look at using that image to create an animation.

 

/// <reference path="phaser.d.ts"/>
class SimpleGame {
    game: Phaser.Game;
    bird: Phaser.Sprite;

    constructor() {
        this.game = new Phaser.Game(640, 480, Phaser.AUTO, 'content', {
            create: this.create, preload:
            this.preload, render: this.render
        });
    }
    preload() {
        // Load the spritesheet containing the frames of animation of our bird
        // The cells of animation are 240x314 and there are 22 of them
        this.game.load.spritesheet("ss", "robin.png", 240, 314, 22);
    }
    render() {
    }
    create() {
        this.bird = this.game.add.sprite(0, 0, "ss", 0);
        // Create an animation using all available frames
        this.bird.animations.add("fly");
        // Play the animation we just created at 10fps, looping forever
        this.bird.play("fly", 10, true);
    }
}

window.onload = () => {
    var game = new SimpleGame();
};

 

And running:

 

 

 

So I mentioned earlier about a texture atlas.  What is that if not a spritesheet?  Well basically it’s the same thing, but with a  table of contents if you will.  The spritesheet relies entirely on images being the same size in a grid like the above.  A texture atlas on the other hand is more flexible.

 

First is the matter of how to create them.  There are actually several applications capable of creating Phaser compatible texture atlases, but TexturePacker is probably the easiest.  I am not going to go into detail on how to use TexturePacker in this post as I have already done so in the past.  For more information click here.

 

There are a couple things to be aware of that are Phaser specific.  For this example I am going to use the animation I created in my Blender tutorial series.  It’s simply the jet in a barrel roll animation, rendered as individual frames, like so:

 

0005000100020003

 

When choosing your project type, Phaser is not listed.  Instead choose Sparrow/Starling:

image

 

Simply drag and drop your frames on animation then set the following settings:

image

 

Size Constraints does not need to be set to Power of 2, but it’s generally a good idea for performance.

Allow Rotation CANNOT be checked, it will break Phaser.

Trim mode is important for this case, as I want to keep the white spaces so the image size remains the same across all animations.  For animations you will generally want to set this to keep your frames the same size.  For non-animations, it can save a great deal of space not selecting this option.

 

When ready click Publish Sprite Sheet at the top button bar.  This will then save an xml file and a png for you to use.  I called mine jet.xml and jet.png, but I am a creative type.

 

Now let’s look at the code for using a texture atlas instead of a sprite sheet… a bit of a warning, it’s awfully same-y.

 

/// <reference path="phaser.d.ts"/>
class SimpleGame {
    game: Phaser.Game;
    jet: Phaser.Sprite;

    constructor() {
        this.game = new Phaser.Game(640, 480, Phaser.AUTO, 'content', {
            create: this.create, preload:
            this.preload, render: this.render
        });
    }
    preload() {
        this.game.load.atlasXML("jet", "jet.png", "jet.xml");
    }
    render() {
    }
    create() {
        this.jet = this.game.add.sprite(0, 0, "jet", 0);
        // Make it bigger so we can see
        this.jet.scale.setMagnitude(3);
        this.jet.animations.add("fly");
        this.jet.animations.play("fly", 15,true);
    }
}

window.onload = () => {
    var game = new SimpleGame();
};

 

And when we run it:

 

 

And that is how you use a spritesheet or texture atlas.

Programming


5. September 2014

 

 

Other than being a word my brain seems to think is spelled incorrectly, Particles are a common part of many games.  Fortunately Phaser has pretty good support for particles.  In this tutorial we are going to take a look at how they are used.

 

First, a quick introduction to particles.  A particle system is simply a mass of things, namely particles.  A particle is often ( as in this case ) a simple sprite.  The entire idea behind a particle system is to control a large number of particles using a single controller.  Particles are commonly used to create effects like fire and smoke, where each dozens, hundreds or thousands of smoke and flame particles are emitted ( pushed ) from the particle emitter.  As the emitter moves, so do the particles emitted from it.  This allows you to define over all behavior in the emitter, not each particle.  If that makes no sense, don’t worry, the examples below should clear it up.

 

Let’s take a look at a very basic emitter.  First we need a particle graphic.  In this case I am using the following graphic:

 

particle

 

It’s a simple transparent png image named particle.png.  Now the code:

 

/// <reference path="phaser.d.ts"/>

class SimpleGame {
    game: Phaser.Game;
    sound: Phaser.Sound;
    emitter: Phaser.Particles.Arcade.Emitter;

    constructor() {
        this.game = new Phaser.Game(640, 480, Phaser.AUTO, 'content', { create: 
                    this.create, preload: this.preload});
    }
    preload() {
        // Load the image we are going to use for our particle
        this.game.load.image("particle", "particle.png");
    }
    create() {
        // Now we are creating the particle emitter, centered to the world
        this.emitter = this.game.add.emitter(this.game.world.centerX, this.game.
                       world.centerY);
        // Make the particles for the emitter to emmit.  We use the key for the 
        particle graphic we loaded earlier
        // We want 500 particles total
        this.emitter.makeParticles('particle', 1, 500, false, false);
        // And BOOM, emit all 500 particles at once with a life span of 10 
        seconds.
        this.emitter.explode(10000, 500);
    }
}

window.onload = () => {
    var game = new SimpleGame();
};

 

Now when you run this code:

 

p1

 

500 particles using our png texture “explode” out of the emitter all at once.  The code is fairly heavily commented to explain what exactly is going on so I am going to move on to the next example.

 

Some ( most? ) of the time, you arent going to want all of your particles exploding all at once, except perhaps if you are modeling an explosion that is, instead you often want them to stream over time, perhaps from a moving source.  Also, you often want to use more than a single particle graphic for variety.  Finally, you often want those particles to physically interact with the world.  This example is going to do all of this.

 

This time we are going to use multiple (poorly edited by me) image files for our particles:

particleparticle2particle3

 

And now the code:

 

/// <reference path="phaser.d.ts"/>

class SimpleGame {
    game: Phaser.Game;
    sound: Phaser.Sound;
    emitter: Phaser.Particles.Arcade.Emitter;
    sprite: Phaser.Sprite;

    constructor() {
        this.game = new Phaser.Game(640, 480, Phaser.AUTO, 'content', {
            create: this.create, preload: this.preload,
            update: this.update
        });
    }
    preload() {
        // This time we have 3 different particle graphics to use
        this.game.load.image("particle", "particle.png");
        this.game.load.image("particle2", "particle2.png");
        this.game.load.image("particle3", "particle3.png");

        this.game.load.image("logo", "gfslogo.png");
    }
    update() {
        // This checks for and handles collisions between our sprite and 
        particles from the emitter
        this.game.physics.arcade.collide(this.sprite, this.emitter);
    }
    create() {
        var start = new Date().getTime();
        for (var i = 0; i < 1e7; i++) {
            if ((new Date().getTime() - start) > 10000) {
                break;
            }
        }
        this.emitter = this.game.add.emitter(0, 0);
        // As you can see, you can pass in an array of keys to particle graphics
        this.emitter.makeParticles(['particle', 'particle2', 'particle3'], 1, 
                                   500, false, false);
        // Instead of exploding, you can also release particles as a stream
        // This one lasts 10 seconds, releases 20 particles of a total of 500
        // Which of the 3 graphics will be randomly chosen by the emitter
        this.emitter.start(false, 10000, 20, 500, true);

        // This line of code illustrates that you can move a particle emitter.  
        In this case, left to right across
        // The top of the screen.  Ignore details tweening for now if it's new, 
        we will discuss later
        this.game.add.tween(this.emitter).to({ x: this.game.width }, 10000,null,
                            true,0,1,true).start();

        // Let's create a sprite in the center of the screen
        this.sprite = this.game.add.sprite((this.game.width / 2) - 100, (this.
                      game.height / 2) - 100, "logo");
        // We want it to be part of the physics of the world to give something 
        for particles to respond to
        // Note, we will cover physics in more detail later ( after tweening 
                                                              perhaps... ;) )
        this.game.physics.enable(this.sprite);
        this.sprite.body.immovable = true;
    }
}

window.onload = () => {
    var game = new SimpleGame();
};

 

And run it:

 

p2

 

As you can see, you can provide multiple particles, move the emitter and have it physically interact with the scene.  Don��t worry over much about tweening or physics, these are two subjects we will cover later in more detail.

 

In these two examples, we’ve looked at particles like you would use for special effects work, a very common situation.  That said, Particles can actually be used to control a large number of game entities that have common over all behavior, but randomized location, rotation, size or scale.  Take for example, a flight of animated birds.  You might want to add birds flying in the background of your game.  Let’s take a look at how to do this!

 

First I am using (a full sized version) of this sprite sheet taken from here.

robin-782x1024

 

It’s an animated sequence of a robin in flight.  It contains 22 frames, each 240x314 pixels in size.

 

Now let’s take a look at the code:

 

/// <reference path="phaser.d.ts"/>


// Create our own Particle class
class MyParticle extends Phaser.Particle {
    elapsedTime: number;
    currentFrame: number;
    static MAX_FRAME: number = 22;
    game: Phaser.Game;

    // In the constructor, randomly pick a starting frame of animation so all 
    the 
    // birds arent animated at the same rate
    constructor(game: Phaser.Game, x: number, y: number, key?: any, frame?: any) 
                {
        this.currentFrame = Math.floor(Math.random() * MyParticle.MAX_FRAME);
        this.elapsedTime = 0;
        this.game = game;

        // Now call Particle's constructor, passing in the spritesheet and frame 
        to use initially
        super(game, x, y, "ss", this.currentFrame);
    }

    update() {
        super.update();

        // Ever 100ms move to the next frame of animation
        this.elapsedTime += this.game.time.elapsed;
        if (this.elapsedTime >= 100) {
            this.currentFrame++;
            if (this.currentFrame > MyParticle.MAX_FRAME) this.currentFrame = 0;
            this.frame = this.currentFrame;
            this.elapsedTime = 0;
        }
    }
}

class SimpleGame {
    game: Phaser.Game;
    sound: Phaser.Sound;
    emitter: Phaser.Particles.Arcade.Emitter;

    constructor() {
        this.game = new Phaser.Game(640, 480, Phaser.AUTO, 'content', {
            create: this.create, preload:
            this.preload, render: this.render
        });
    }
    preload() {
        // Load the spritesheet containing the frames of animation of our bird
        // The cells of animation are 240x314 and there are 22 of them
        this.game.load.spritesheet("ss", "robin.png", 240, 314, 22);
    }
    render() {
    }
    create() {
        // Now we are creating the particle emitter, centered to the world
        this.emitter = this.game.add.emitter(this.game.world.centerX, this.game.
                       world.centerY);

        this.emitter.particleClass = MyParticle;
        this.emitter.makeParticles();
        
        // In this case, we dont want gravity affecting the birds and we dont 
        want them to rotate
        this.emitter.gravity = 0;
        this.emitter.minRotation = 0;
        this.emitter.maxRotation = 0;

        // Now start emitting particles.  Total life of 1000 seconds, create one 
        per 500ms ( 2/sec )
        // and create a total of 100 birds.
        this.emitter.start(false, 100000, 500, 100, true);
    }
}

window.onload = () => {
    var game = new SimpleGame();
};

 

And when run:

 

p3

 

The terrible graphics are a side effect of being converted to an animated GIF that would take forever to download!

 

It just dawned on me that I haven’t actually covered Spritesheets yet… oops.  Hey, this is how you use a spritesheet! :)  Don’t worry if you struggle with the spritesheet portions, we will cover that later as well.  The important part here is the Particle itself.  In this example we extend the class Particle to create our own Particle class.  This class then handles updating itself resulting in the animation of the bird.  Obviously you could put a great deal more logic in there, although be sure to keep things pretty light computationally, especially if you intend to create a number of them.

 

This example actually illustrates a couple of really nice features of TypeScript, but maps nicely to Phaser’s JavaScript.  The first in the concept of a constructor.  This is code that is called as the object is created.  The next more important concept is class and extend.  In this case we are extending an existing JavaScript class, Particle.  A quick look behind the curtains now.

 

In TypeScript we write:

 

class MyParticle extends Phaser.Particle

 

This results in the JavaScript

 

var __extends = this.__extends || function (d, b) {
    for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
    function __() { this.constructor = d; }
    __.prototype = b.prototype;
    d.prototype = new __();
};
// Create our own Particle class
var MyParticle = (function (_super) {
    __extends(MyParticle, _super);

 

Pretty cool stuff, and certainly easier to read and maintain.

 

A Small Bug

 

While writing this I ran into a small bug I figured I should make you aware of ( and one of the downsides of working with TypeScript ).  In the code sample we had the following line:

 

this.emitter.particleClass = MyParticle;

 

This line is specifying the type of class to use for a Particle, no an instance of the class.  Unfortunately the Phaser.d.ts file is incorrect in it’s definition.  It instead expects particleClass to receive a Phaser.Particle instance.  This is wrong ( and took some time to route out ).  In the definition, if not fixed by the time you read this, make the following edit to Emitter:

 

particleSendToBack: boolean;
// MJF Fix particleClass: Phaser.Sprite;
particleClass: any;

 

Hopefully that will be fixed by the time you read this.

 

Programming


GFS On YouTube

See More Tutorials on DevGa.me!

Month List