Subscribe to GameFromScratch on YouTube Support GameFromScratch on Patreon

27. November 2014

 

 

Now we are going to look at using the P2 Physics engine.  Truth of the matter is, the experience is very similar to what we just experienced with Arcade physics.  The biggest difference is P2 is more accurate, has greater options for simulation and critically, takes up more CPU power.

 

Let’s jump in straight away with a simple example.  We are going to load two identical sprites, anchor one and create a spring between them.  Code time!

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

    constructor() {
        this.game = new Phaser.Game(640, 480, Phaser.AUTO, 'content', {
            create: this.create, preload: this.preload
        });
    }
    preload() {
        this.game.load.image("decepticon", "decepticon.png");
    }
    create() {
        this.player1 = this.game.add.sprite(this.game.width/2, 0 + 50, "decepticon");
        this.player2 = this.game.add.sprite(this.game.width/2, this.game.height, "decepticon");

        this.game.physics.startSystem(Phaser.Physics.P2JS);

        // Enabled physics on our sprites
        this.game.physics.p2.enable([this.player1, this.player2]);

        // Make our one body motionless
        this.player1.body.static = true;
        
        // Now create a sprite between our two bodies, parameters are rest length, stiffness and damping
        // Rest length is the length of the spring at rest ( where it's not under pressure )
        // Stiffness is the resistance to movement of the spring
        // Damping determines how fast the spring loses it's "boing"  Our low damping keeps our spring "boinging"
        // Boing is a word I made up to describe the up and down motion of a spring doing it's spring thing
        this.game.physics.p2.createSpring(this.player1, this.player2, 200, 2, 0.3);

        // Lets loop a timed event every 10 seconds that moves the one end of our spring back to the start
        // Mostly just so people that didn't see it run the first time in the browser have something to see!
        this.game.time.events.loop(Phaser.Timer.SECOND * 10, () => {
            this.player2.body.x = this.game.width/2;
            this.player2.body.y = this.game.height;
            }, this);

    }
}

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

The code is fairly well commented, so I'll just go through the gist of what's happening here.  Just like before, you have to start the Physics subsystem, this time we pass in Phaser.Physics.P2JS.  You also have to register your objects with the physics system.  In this case we do it by passing an array of Sprite to p2.enable();  We set one of our physics bodies to static, which will cause it to not be moved or updated by the physics system.  We then create a spring between the two sprites.  This will cause the second sprite to “spring” toward the first, until the rest length is met ( plus any momentum ), then the spring will, well, spring.  Finally, just to make the demo run a bit better in the browser, we schedule a looping event every 10 seconds that resets the second sprites physics body back to the starting position to start the whole game all over again. 

 

Here is our code running in the browser:

 

One of the big advantages to P2 is it can use Polygon data for more precise collision calculates than body boxes.  Consider the following sprite:

 

megatron

 

When doing bounding box based collisions tests, this would be considered a “hit”:

 

BoundingBox

 

Ideally instead we should create a tighter bounding volume for our collision tests, like so:

BoundingPoly

 

Well, the good news is we can, but we need a third party editor to create the bounding volumes.  One such tool and the one I am going to use in this example is Physics Editor by CodeAndWeb.  It’s commercial software, but there is a free version with the following restrictions:

 

image

 

It can be purchased currently for about $20.

 

CURRENTLY, I COULD NOT GET THE CURRENT WINDOWS VERSION TO EXPORT!

There is a DLL missing, I’ve reported it to the developer, for now instead use the older version available here.

 

For this, I am just using the unregistered version.  Load it up, then click Add Sprites:

image

 

Navigate to the sprite you want to work with and click OK.  It should appear in the window like so:

image

 

I’m full of serious lazy, so I’m going to let the app do the work, simply click the Shape Tracer icon:

image

 

Now in the resulting dialog, play with the tolerance and alpha value until you have a bounding volume you like with a vertex count you can deal with:

image

 

Once you are happy with it, set the Exporter on the right to Lime + Corona ( JSON ).

image

 

Save the resulting file to your project directory.

 

Now time to actually use the results in Phaser:

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

    constructor() {
        this.game = new Phaser.Game(640, 480, Phaser.AUTO, 'content', {
            create: this.create, preload: this.preload
        });
    }
    preload() {
        this.game.load.image("megatron", "megatron.png");
        this.game.load.physics("physicsInfo", "physics.json");
    }
    create() {
        this.player1 = this.game.add.sprite(0, 0, "megatron");
        this.player2 = this.game.add.sprite(0, 0, "megatron");

        // Being lazy, positioning sprite after creation so we have a valid width/height
        this.player1.position.set(this.player1.width / 2, this.player1.height / 2);
        
        // Now another sprite on the right side of the screen, down slightly
        this.player2.position.set(this.game.width - (this.player2.width / 2),  this.player2.height / 2 + 85);

        

        this.game.physics.startSystem(Phaser.Physics.P2JS);
        
        // Passing in true while enabling physics on an object causes the debug renderer to draw the physics body
        this.game.physics.p2.enable([this.player1, this.player2], true);

        // You need to call clearShapes() to get rid of the existing bounding box
        this.player1.body.clearShapes();
        this.player2.body.clearShapes();

        // Now load the polygon bounding data we created externally
        this.player1.body.loadPolygon("physicsInfo", "megatron");
        this.player2.body.loadPolygon("physicsInfo", "megatron");

        // Now let's get this party started
        this.player2.body.moveLeft(80);

        // Finally, when the collision occurs, move back to the beginning and start over
        this.player2.body.onBeginContact.add((body, shapeA, shapeB, equation) => {
            this.player2.body.x = this.game.width - (this.player2.width / 2);
            this.player2.body.y = this.player2.height / 2 + 85;
            }, this);
    }
}

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

 

WARNING!  When using P2 physics, if your physics body starts even slightly outside the bounds of the screen, it will start with forces applied against it!

 

When you run this code, it creates two identical Megatrons, on each side of the screen, slightly offset, then sends one towards the other… ok, let’s just watch it:

 

As you can see, using Polygon volumes allow for much greater precision in your collision tests.  Using simple bounding boxes, the collision would occur a great deal earlier.

 

There is a lot more about P2 physics, but in all honesty, Polygon’s are probably the single biggest reason to use it.  Again it is important to remember that P2 is the slowest option, but the most precise.  Also, you have the option of mixing and matching physics engines within the same game.

 

Programming , ,

7. November 2014

 

 

I’ve already cheated a few times using physics with the caveat that “I will cover this later”.  Well, welcome to later!  One thing you should be aware of right away is that there are a number of different physics engines available in Phaser.  In this particular tutorial we are going to cover Arcade physics, but there is also P2, Ninja and coming soon as a premium plugin, Box2D.

 

You may be thinking to yourself… huh?  Why the hell are there 3+ physics engines?   Let me try to break it down as best as I understand it.  First thing to know is, there is zero overhead from all of these systems, you need to enable them before you can use them, so you only pay the costs of what you need.

 

The Physics systems in Phaser are:

  • Arcade is a light weight engine, not the most accurate or full featured, but fast.  It’s also historically what was in Phaser all along.
  • P2 is an existing Javascript physics library.  It’s far more featured than Arcade, but also a lot slower as there is a ton more calculations going on behind the scenes.
  • Ninja… well Ninja I don’t entirely get the purpose behind.  As best I understand it, the author of Phaser, Richard Davey, wrote it a while ago and ported it from Flash to Phaser.  I think it falls somewhere in between Arcade and P2 in the feature/performance scale.  It’s stripped down in functionality from P2.
  • Box2D, well first off, it’s not available yet.  It is about as close to industry standard as 2D physics systems get though.

 

You can also use more than one physics system at a time, but they wont interact.  So if you have something either with tons of them in the scene ( say bullets or particles ) or where you need only basic physics, you can use Arcade.  Then if you require more accuracy, use P2.

 

This particle tutorial is going to look at Arcade Physics.  Let’s start with a very simple example.  We are going to enable physics, turn on gravity and enabled a sprite to be a physics body.

/// <reference path="phaser.d.ts"/>
class SimpleGame {
    game: Phaser.Game;
    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.image("decepticon", "decepticon.png");
    }
    render() {
        // This renders debug information about physics bodies
        this.game.debug.body(this.player);
    }
    create() {
        this.player = this.game.add.sprite(this.game.width / 2, 0, "decepticon");

        // Start the ARCADE Physics system
        this.game.physics.startSystem(Phaser.Physics.ARCADE);
        
        // Enable physics on the player sprite
        this.game.physics.enable(this.player, Phaser.Physics.ARCADE);

        // Set the sprite to collide with the worlds edge
        this.player.body.collideWorldBounds = true;
        // And set bounce in the Y axis ( called restitution in most physics system ) to 1, 
        // which will make it bounce equal to 100 %
        this.player.body.bounce.y = 1;

        // Set the physics engines overall gravity.  98 == 98 pixels per second in this demo
        this.game.physics.arcade.gravity.y = 98;
    }
}

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

 

Run it:

 

 

This example is pretty heavily commented, so I wont go into much detail.  It illustrates a few key concepts.  First, you need to start the physics subsystem before you can use it.  Second, you need to initialize a sprite to be a physics object.  Finally, you can render debug information using game.debug.body(), which will draw the bounding box as seen by the physics engine.  This can be incredibly useful for debugging physics simulation problems.

 

Now one of the very first things people are going to want to use a physics engine for is collision detection, so lets do that next!

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

    constructor() {
        this.game = new Phaser.Game(640, 480, Phaser.AUTO, 'content', {
            create: this.create, preload: this.preload,
            render: this.render, update: this.update
        });
    }
    preload() {
        this.game.load.image("decepticon", "decepticon.png");
    }
    update() {
        // Now check for a collision between objects
        this.game.physics.arcade.collide(this.player1, this.player2);
    }
    render() {
    
    }
    create() {
        this.player1 = this.game.add.sprite(this.game.width, this.game.height / 2 - 50, "decepticon");
        this.player2 = this.game.add.sprite(0, this.game.height / 2 - 50, "decepticon");

        this.game.physics.startSystem(Phaser.Physics.ARCADE);

        // You can enable multiple bodies at once by passing in an array like so:
        this.game.physics.arcade.enable([this.player1, this.player2]);
        this.player1.body.collideWorldBounds = true;
        this.player2.body.collideWorldBounds = true;

        // Set the players to bounce along x axis instead
        this.player1.body.bounce.x = 1;
        this.player2.body.bounce.x = 1;

        // Now set them moving.  Move to the center of the screen accelerating to 100pixels per second
        this.game.physics.arcade.accelerateToXY(this.player1, this.game.width / 2,
                                                this.game.height / 2 - 50, 100);
        this.game.physics.arcade.accelerateToXY(this.player2, this.game.width / 2,
                                                this.game.height / 2 - 50, 100);
        
        this.game.physics.arcade.gravity.y = 0;
    }
}

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

And the results:


 

This example shows us a couple things.  Most important is for collisions to occur you need to test for them using collide().  You can also see from this example that it’s possible to initialize multiple physics bodies at once by passing all the sprites in to game.physics.arcade.enable as an array.  This demo also illustrates that you can easily turn gravity off in a simulation.

 

In this particular demo we used AccelerateToXY to get our bodies moving.  There are a number of other functions for moving physics bodies, checking for intersections, measuring distances and angles available in the Physics.Arcade class, they work fairly straight forward so I leave exploring them as an exercise for the reader.  There are a few final concepts I want to touch on before moving on.

 

The first is collision handling.  The above example simply tested if a collision happened.  Phaser Arcade physics however give you a great deal more control than that, as will now see.  When you call collide() you have the option of passing in a pair of callbacks, like so:


    update() {
        // Now check for a collision between objects
        this.game.physics.arcade.collide(this.player1, this.player2,
            // This callback is called when a collision occurs
            // In this example we scale object1 on collision until its 2x bigger in size
            (object1: any, object2: any) => {
                // object1 and object2 will be either of type Sprite, Group, Tilemap or Particle Emitter
                if (object1 instanceof (Phaser.Sprite)) {
                    (<Phaser.Sprite>object1).scale.multiply(1.1, 1.1);
                    if ((<Phaser.Sprite>object1).scale.x > 2) {
                        (<Phaser.Sprite>object1).scale.set(1, 1);
                    }
                }
            },
            // This callback is called for additional testing, AKA user driven logic on if a collision occurs
            // If you return true, a collision occured, if you returned false, a collision doesn't occur
            // In this example, object checks the direction in the X axis it's moving, if moving right to left
            // then a collision wont occur.  As a result, the first collision test 
            //both objects will pass through each other.
            (object1: any, object2: any) => {
                if (object1 instanceof (Phaser.Sprite)) {
                    if ((<Phaser.Sprite>object1).deltaX < 0)
                        return false;
                    else
                        return true;
                    }
            },
            this);
    }

Which when run results in:


The code comments explain most of what happens.  Basically you have a pair of callbacks available.  The first one is the action to perform IF a collision occurs, in addition to any action the physics engine is going to take that is.  In this simple example, we scale one of the two colliding objects up until it’s size has doubled.  As you can see, the colliding and collided objects are passed in to this function.  The type of this object can be a Sprite, Group, Particle Emitter or Tilemap.  We actually used Arcade Physics in earlier tilemap and particle tutorials if you want more details on collisions between these types. 

 

The second callback determines if a collision occurs at all.  Returning false out of that function means that no collision occurred, while true indicates one did.  If you run this example ( click here to open it in a new browser as it’s probably already run too far ), you will notice that on the first pass, no collision occurs.

 

The final thing I want to touch on is grouping.  As mentioned above, in the collision callbacks, one of the types of collisions that can occur is between groups.  I am not going to go into detail as I already covered grouping earlier, but I wanted you to be aware that you can group sprites together then perform collisions that way.  This is handy when you have a large number of similar sprites, such as bullets, because frankly doing a collide() call for each possible combination get’s old quickly!

 

In the future I will look at some of the other physics systems, but for quick and dirty collisions and simple physics, Arcade Physics should be enough.

 

Programming , ,

6. November 2014

 

I will admit, I am somewhat late to this party… I’ve shared a project or two to Github in the past, but I’ve never really embraced it.  It’s one of those things I should probably change and I will start to address. 

 

So here we are starting with the code samples for the TypeScript with Phaser series.  For many tutorials I often didn’t keep the solutions I used to create examples, so I have nothing to share.  However for this series, I have done all of the work in a single Visual Studio solution, so it made pushing it up to Github easy.  You will find 90% of the examples from that series are now available on Github.  For a few minor samples, I simply made changes to the base project to come up with the derived code, so you wont find those ones.  I pushed everything up, so that means all the assets used are included too.  Since I continue to use this single solution for the entire project, as I add new examples, they will be available on Github as well.

 

You can access all the samples here on Github.

 

image

 

I will be the first to admit, I know very little about Github as anything other than a consumer, so expect so tales of epic stupid while I get the hang of things.  Right now there are 29 projects in the PhaserTypescript repository, although PhaserArcade is a WIP ( guess what I’m working on… ).

 

Let me know if I’ve made any mistakes here. Hope this code proves useful to somebody.

Programming , ,

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 , , , ,

Month List

Popular Comments