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

 

 

In the previous tutorial we took a look at creating, loading and displaying a tilemap in Phaser and for many simple projects this may be enough.  That said, there are two very common scenarios this doesn’t really address, and we will look at those in this tutorial.  The first is positioning a sprite within a tilemap.  The second is collision detections between tiles and sprites.

 

Placing a sprite within a tilemap is a pretty common behavior, but the way you deal with it isn’t immediately obvious in Phaser.  To understand what I am going on about it’s good to understand how layers of tilemaps work.  You may recall in our previous example, our tilemap was composed on three layers, one for the background, one for the midground (a word I apparently made up) and one for the foreground.  Basically the background is where you would put the stuff that happens behind the scene, things like clouds or the blue sky for example.  The midground is generally where the bulk of the stuff in your world would go.  The foreground then is the stuff drawn on top of the midground.

 

Quite often your playersprite will then be drawn in front of the foreground.  That said, what happens when your player is behind something in the world, such as say… a shrubbery?  How do we deal with this?  Well first, let’s visualize how the layers of a tilemap come together.

 

No better way than an image, right?

 

Layers

 

Think of each layer of tiles as sheets laid one over the next.  The top most layer obscuring the contents behind it, and that layer obscuring the contents behind it.

 

So, in Phaser, what determines draw order?  Simple, the order they were added in.  Change the order layers are drawn, you change what draws on top of what.  Know this then, how do we could we for example draw our character sprite between the foreground and midground layer so it appears behind the chandelier, like so:

 

 

Layers2

 

 

The answer is actually quite simple but possibly a bit confusing, let’s look at the code:

 

/// <reference path="phaser.d.ts"/>
class SimpleGame {
    game: Phaser.Game;
    map: Phaser.Tilemap;
    player: 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.tilemap("ItsTheMap", "map.json", null, Phaser.Tilemap.TILED_JSON);
        this.game.load.image("Tiles", "castle_0.png");
        this.game.load.image("Decepticon", "decepticonLarge.png");
    }
    render() {

    }
    create() {
        this.map = this.game.add.tilemap("ItsTheMap", 32, 32, 50, 20);
        this.map.addTilesetImage("castle_0", "Tiles");

        this.map.createLayer("Background").resizeWorld();
        this.map.createLayer("Midground");
        this.map.createLayer("Foreground");

        this.player = new Phaser.Sprite(this.game,200,50,"Decepticon");
        this.game.world.addAt(this.player, 2);
    }
}

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

 

And when we run it:

image

 

Note the order we called createLayer matches the order we want the layers drawn, from back to front.  After that we load our sprite then do something a bit different from what we’ve done in the past.  Previously we just added Sprites using this.game.add().  Now however we want a bit more control of where they are added.  This is why we created our Sprite instead using new, then explicitly added it to the world using addAt().  By adding it at index 2 ( the 3rd item ) this means we will be between the mid and foreground in the world list.

 

You should be aware however that this is incredibly fragile an approach.  You can only rely on layers being where they are because they are the only other objects we’ve created.  In a non-trivial example, you will dozens or hundreds of other objects in your scene, this may not be as easy to figure out.  There are of course alternatives.  One of the easiest, and possibly crudest options, would be too iterate through the world, find the index of layer you want to insert before and then insert like so:

 

        var index: number;
        this.game.world.forEach((child) => {
            index++;
            if (child.layer.name = "Foreground")
                index = child.index;
        }, this, false);
        this.game.world.addAt(this.player, index);

 

I suppose I should point out this particular solution iterates through every item in the world, even if the first child is what you are looking for. Also, it doesn't take into account the possibility that the given child doesn't even exist, which is probably a bad idea. That all said, I think you get the gist of how this works.  As you may notice, the world variable is pretty important, as essentially it is the scene graph, the source of all things to be rendered.  At the end of the day though, it’s just a group that we covered earlier.

 

Ok… that was a really long way of saying the order you add things to the world is really important… let’s move on, collisions.

 

Quite often you are going to want to test to see if “stuff” (scientific term there… ) hits other “stuff”.  In this particular case, we want to see if our game sprite collides with the “floor”.  First lets take a look at adding physics to our game sprite.  I’ve used physics in past tutorials, but havent gone into detail how these things work… and I am not going to here either.  For now just think of it as the work of moon wizards.  I will cover physics at a later point, I promise!

 

So, back to enabling physics and gravity for game sprites.  Here’s how:

 

    create() {
        // Enable the physics system in Phaser
        this.game.physics.startSystem(Phaser.Physics.ARCADE);
        this.map = this.game.add.tilemap("ItsTheMap", 32, 32, 50, 20);
        this.map.addTilesetImage("castle_0", "Tiles");

        this.map.createLayer("Background").resizeWorld();
        var world = this.map.createLayer("Midground");
        this.map.createLayer("Foreground");

        this.player = new Phaser.Sprite(this.game, 200, 50, "Decepticon");
        // Apply physics to our game sprite
        this.game.physics.enable(this.player, Phaser.Physics.ARCADE);
        // Turn on gravity.  10pixels / second along the y axis
        this.player.body.gravity.y = 10;

        this.game.world.addAt(this.player, 3);
    }

 

The comments explain the basics of what’s going on, like I said, I will go into a bit more detail later.  Now if you run the code with the above changes the player sprite ( the Decepticon logo ) will slowly fall to the bottom of the screen, to infinity and beyond.

 

Now what we would prefer to see is the sprite stop when it collided with the tiles composing the floor.  This takes a bit of understanding of how tilemaps are actually stored as data.  Open up map.json and you will see a layer contains an array called data full of tiles that make up the layer, like so:

 

image

 

Each of those indices present a location within your sprite image.  Let’s take a look back in Tiled for a second.

 

image

 

You can see the ID of each tile by simply clicking it in the Tilesets window.  In this case we are going to want the ID of each red topped brick.  Specifically we want the ID of the tiles that make up these particular tiles

 

image

 

In my particular case, the IDs were 32,33,34,35 and 36.  Now that we know the IDs of the tiles we want to collide with, lets set that up.  Code time!

 

/// <reference path="phaser.d.ts"/>
class SimpleGame {
    game: Phaser.Game;
    map: Phaser.Tilemap;
    layer: Phaser.TilemapLayer;
    player: Phaser.Sprite;
    
    constructor() {
        this.game = new Phaser.Game(640, 480, Phaser.AUTO, 'content', {
            create: this.create, preload:
            this.preload,update:this.update, render: this.render
        });
    }
    preload() {
        this.game.load.tilemap("ItsTheMap", "map.json", null, Phaser.Tilemap.TILED_JSON);
        this.game.load.image("Tiles", "castle_0.png");
        this.game.load.image("Decepticon", "decepticonLarge.png");
    }
    update() {
        // You actually need to perform the collision test between the map and player sprite
        this.game.physics.arcade.collide(this.player, this.layer);
    }
    render() {
        // Display the outline of the physics body
        this.game.debug.body(this.player);
    }
    create() {
        // Enable the physics system in Phaser
        this.game.physics.startSystem(Phaser.Physics.ARCADE);
        this.map = this.game.add.tilemap("ItsTheMap", 32, 32, 50, 20);
        this.map.addTilesetImage("castle_0", "Tiles");

        this.map.createLayer("Background").resizeWorld();
        this.layer = this.map.createLayer("Midground");
        this.map.createLayer("Foreground");

        this.player = new Phaser.Sprite(this.game, 200, 40, "Decepticon");
        // Apply physics to our game sprite
        this.game.physics.enable(this.player, Phaser.Physics.ARCADE);
        // Turn on gravity.  10pixels / second along the y axis
        this.player.body.gravity.y = 10;
        this.player.body.collideWorldBounds = true;

        // Now setup the tiles in our midground layer for collisions
        // When using multiple layers it is critical you specify the layer the collisions occur on!
        this.map.setCollisionBetween(32, 36,true,this.layer.index,true);
        

        this.game.world.addAt(this.player, 2);

        // Add a keyboard handler on 'R' pressed the resets the sprite to it's starting position
        this.game.input.keyboard.addKey(Phaser.Keyboard.R).onUp.add(() => {
            this.player.position.set(200, 40);
        });
    }
}

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

 

 

Here is the code running.

 

 

Click in the IFrame and press R to reset the sprite to it’s starting position.

 

Most of the important bits are commented in the source code, but a few things are worth noting.  The most important is how you add collision tests to individual tiles within the world.  As mentioned earlier, you need the tile ID of the tile within the layer.  You then use setCollision methods to mark which tiles perform collisions.  In this example we used setCollisionBetween() which allows you to specify a range of tiles to collide with.  There is also a version that takes an individual tile ID as well as one that takes an array.  The critical part of this call is you have to provide the layer where the collision takes place.  Also of importance is the call to physics.arcade.collide() which tells Phaser to check for a collision between that layer and your player sprite.

 

One other thing you may notice is in render(), I call game.debug.body(this.player).  This causes the renderer to draw a bounding box around the physics shape of our sprite.  This is important because it exposes a very common bug that I thought I would address.  Notice when you run the applicaion, once gravity is done, our image is resting above the ground like this:

 

image

 

This is because our source image has some empty pixels.  The physics bounding volume is going to be around the entire sprite, not just drawn pixels.  If you are using physics, be sure your image is cropped as much as possible!

 

So that illustrates how to insert a sprite between tilemap layers and how to perform collisions against tiles.  That should be the majority of what you need to get started using tilemaps.

 

Before we continue, I should answer a commonly asked question.  What about isometric maps?  Yes, Tiled can export isometric tilemaps, but currently Phaser does not support them.  There are some third party code samples to load them, but nothing in the core as of yet.

 

Programming


22. October 2014

 

 

In this tutorial we are going to look at loading and using Tiled TMX maps.  Tiled is a free, open sourced map editor, and TMX is the file format it outputs.  You basically use it to “paint” levels using one or more spritesheets containing tiles, which you then load and use in your game.

 

Here is Tiled in action, creating the simple map I am going to use in this example:

image

 

By the way, I downloaded the tile graphics from here.  Additionally, you can download the generated TMX file we will be using here.

 

I am not going to go into detail on using the Tiled editor.  I actually covered this earlier here.  For Phaser however, just be certain you export as either JSON or CSV format and you should be good to go.

 

Now let’s look at some code to load the tile map.

 

 

/// <reference path="phaser.d.ts"/>
class SimpleGame {
    game: Phaser.Game;
    map: Phaser.Tilemap;
    
    constructor() {
        this.game = new Phaser.Game(640, 480, Phaser.AUTO, 'content', {
            create: this.create, preload:
            this.preload, render: this.render
        });
    }
    preload() {
        this.game.load.tilemap("ItsTheMap", "map.json", null, Phaser.Tilemap.TILED_JSON);
        this.game.load.image("Tiles", "castle_0.png");
    }
    render() {

    }
    create() {
        this.map = this.game.add.tilemap("ItsTheMap", 32, 32, 50, 20);
        this.map.addTilesetImage("castle_0", "Tiles");

        this.map.createLayer("Background").resizeWorld();
        this.map.createLayer("Midground");
        this.map.createLayer("Foreground");
        
        
        this.game.camera.x = this.map.layers[0].widthInPixels / 2;
        this.game.camera.y = 0;

        this.game.add.tween(this.game.camera).to({ x: 0 }, 3000).
to({ x: this.map.layers[0].widthInPixels }, 3000).loop().start(); } } window.onload = () => { var game = new SimpleGame(); };

 

And when you run it… assuming like me you are using Visual Studio 2013 you will probably see:

image

 

Hmmmm, that’s not good.  Is there something wrong with our tilemap?  Did we make a mistake?

 

Nope… welcome to the wonderful world of XHR requests.  This is a common problem you are going to encounter over and over again when dealing with loading assets from a web server.  If we jump into the debugger, we quickly get the root of the problem:

 

image

 

Let’s look closely at the return value in xhr.responseText:

Ohhh. it’s an IIS error message and the key line is:

The appropriate MIME map is not enabled for the Web site or application.

Ah…

 

See, Visual Studio ships with an embedded version of IIS called IIS Express, and frankly, IIS Express doesn’t have a clue what a JSON file is.  Let’s solve that now.  If you created a new TypeScript project in Visual Studio, it should have created a web.config file for you.  If it didn’t create one and enter the following contents:

<?xml version="1.0" encoding="utf-8"?>
<!--
  For more information on how to configure your ASP.NET application, please visit
  http://go.microsoft.com/fwlink/?LinkId=169433
  -->
<configuration>
  <system.web>
    <compilation debug="true" targetFramework="4.5" />
    <httpRuntime targetFramework="4.5" />
  </system.web>
  <system.webServer>
    <staticContent>
      <mimeMap fileExtension=".json" mimeType="application/json" />
    </staticContent>
  </system.webServer>
</configuration>

 

Now the code should run without error

I should take a moment to point out that this is an entirely Visual Studio specific solution.  However, this particular problem is by no means limited to IIS Express.  I documented a very similar problem when dealing with WebStorm’s integrated Chrome plugin.  If your loadJson call fails, this is most likely the reason why!  Well that or you typo’ed it. :)

 

Ok, assuming everything is configured right,now we should see:

 

 

By the way, you may have to click on the to get it to start rendering.

 

Most of the loading code should look pretty familiar by now, Phaser is remarkably consistent in its approach.  There are a few things to be aware of though from that code.  First, the order you create layers in is important.  In Tiled I created 3 layers of tiles.  A solid background layer named “background”, a middle layer with most of the tiles in it called “midground” then a detail layer for the topmost tiles named “foreground”.  Think of rendering tiles like putting stickers on a flat surface… the front most stickers will obscure the ones that are behind them.  The same is true for tiles.  There are other options in tiled for creating foreground and background layers, but I stuck with normal tile layers for ease.  Just no that more efficient options exist.

 

The next thing to be aware of is when I called addTilesetImage, that is the same image filename that I provided to Tiled.  It is important that you use the same graphics files and names between Tiled and your code.  The next thing worth noticing is the call to resizeWorld() I made when loading the first tiled layer.  This simply set’s the world’s dimensions to be the same size as the tile layer you specified.  Since all the tile layers are the same size, you could have called it on any of them.  Finally, we made a simple tween that pans the camera from one end of the level to the other and back.

 

There is more to touch on with tiles, but I will have to cover that in later post(s).

 

Programming


6. October 2014

 

 

In today’s tutorial we are going to cover the simple but powerful concept of grouping in Phaser.  As the name suggested, grouping allows you to group like minded Sprites together.  Probably easiest to jump right in with a simple example:

 

/// <reference path="phaser.d.ts"/>
class SimpleGame {
    game: Phaser.Game;
    sprite: Phaser.Sprite;
    group: Phaser.Group;
    
    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.group = this.game.add.group();
        this.group.create(0, 0, "decepticon");
        this.group.create(100, 100, "decepticon");
        this.group.create(200, 200, "decepticon");

        this.game.add.tween(this.group).to({ x: 250 }, 2000,
            Phaser.Easing.Linear.None, true, 0, 1000, true).start();
    }
}

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

 

And run it:

 

 

As you can see, all objects in the group are updated as the group is updated.  You may notice we created the sprites directly in the group using Group.create, but we didn’t have to.  We could have just as easily done:

 

    create() {
        this.group = this.game.add.group();
        var sprite1 = this.game.add.sprite(0, 0, "decepticon");
        var sprite2 = this.game.add.sprite(100, 100, "decepticon");
        var sprite3 = this.game.add.sprite(200, 200, "decepticon");
        this.group.add(sprite1);
        this.group.add(sprite2);
        this.group.add(sprite3);

        this.game.add.tween(this.group).to({ x: 250 }, 2000,
            Phaser.Easing.Linear.None, true, 0, 1000, true).start();
    }

 

You can also add groups to groups, like so:

 

    create() {
        this.group = this.game.add.group();
        this.group2 = this.game.add.group();

        this.group.create(0, 0, "decepticon");

        this.group2.create(100, 100, "decepticon");
        this.group2.create(200, 200, "decepticon");

        this.group.add(this.group2);

        this.game.add.tween(this.group).to({ x: 250 }, 2000,
            Phaser.Easing.Linear.None, true, 0, 1000, true).start();
    }

 

The above code performs identically to the earlier example.  This can provide a great way to organize your game into logical entities, such as a group for the background, a group for scrolling foreground clouds, a group for bullets, etc.

 

Grouping things together is all nice and good, but if you can’t do anything to the group, it’s mostly just pointless.  Fortunately then, there is quite a bit you can do with a group.  You can loop through them:

 

    create() {
        this.group = this.game.add.group();

        this.group.create(0, 0, "decepticon");
        this.group.create(100, 100, "decepticon");
        this.group.create(200, 200, "decepticon");

        // Set each item in the group's x value to 0
        this.group.forEach((entity) => {
            entity.x = 0;
        }, this, false);

        this.game.add.tween(this.group).to({ x: 250 }, 2000,
            Phaser.Easing.Linear.None, true, 0, 1000, true).start();
    }

 

You can sort them:

 

    create() {
        this.group = this.game.add.group();

        this.group.create(0, 0, "decepticon");
        this.group.create(100, 100, "decepticon");
        this.group.create(200, 200, "decepticon");

        // Sort group by y coordinate descending
        this.group.sort("y", Phaser.Group.SORT_DESCENDING); 
        this.game.add.tween(this.group).to({ x: 250 }, 2000,
            Phaser.Easing.Linear.None, true, 0, 1000, true).start();
    }

 

You can update a property on all group members at once:

 

    create() {
        this.group = this.game.add.group();

        this.group.create(0, 0, "decepticon");
        this.group.create(100, 100, "decepticon");
        this.group.create(200, 200, "decepticon");

        // set the alpha value of all sprites to 50%
        this.group.setAll("alpha", 0.5);

        this.game.add.tween(this.group).to({ x: 250 }, 2000,
            Phaser.Easing.Linear.None, true, 0, 1000, true).start();
    }

 

Running:

 

 

You can get the index of any item within the group:

 

    create() {
        this.group = this.game.add.group();

        var sprite1 = this.group.create(0, 0, "decepticon");
        this.group.create(100, 100, "decepticon");
        this.group.create(200, 200, "decepticon");
        this.group.sort("y", Phaser.Group.SORT_DESCENDING);

        var index = this.group.getIndex(sprite1);
        this.game.add.text(0, 0, "Sprite1's index is:" + index,
            { font: "65px Arial", fill: "#ff0000", align: "center" },
            this.group); // Index should be 2

        this.game.add.tween(this.group).to({ x: 250 }, 2000,
            Phaser.Easing.Linear.None, true, 0, 1000, true).start();
    }

 

Running:

 

 

And as you might be able to see from the above example, you can also add text objects directly to groups!

One other important concept of Groups is being dead or alive.  There are all kinds of methods for checking if an entity is alive or not, like so:

 

    create() {
        this.group = this.game.add.group();

        var sprite1 = this.group.create(0, 0, "decepticon");
        this.group.create(100, 100, "decepticon");
        this.group.create(200, 200, "decepticon");


        sprite1.alive = false;
        this.group.forEachDead((entity) => {
            entity.visible = false;
        }, this);

        this.game.add.tween(this.group).to({ x: 250 }, 2000,
            Phaser.Easing.Linear.None, true, 0, 1000, true).start();
    }

 

This kills off the first of the three sprites, leaving you:

 

 

This tutorial only scratched the surface on what groups can do.  Simply put, they are a convenient data type for logically holding your game objects.  The only thing I didn’t mention is what happens when a group doesn’t have a parent.  In this situation, that parent is the games’ World, which… is a group.

 

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

 

 

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


See More Tutorials on DevGa.me!

Month List