Wednesday, April 13, 2016

Use Tiled's Map Background Color in Phaser

I actually did some work on my Phaser platformer this week! Yeah! I resolved an issue that was submitted on GitHub concerning the water physics in Level 7, and I started thinking some more about another thing which had been bothering me.

Even though I can set a map's background color in the Tiled map editor, Phaser doesn't parse that property when it builds a Tilemap object. I had been keeping track of the background colors for each level separately, but that violates one of my principles - the map editor should be the one and only source of data about each level map.

The Background Color map property in Tiled

I was able to make a few minor changes to work around this limitation. In the stage's create function, I first pull the tilemap data manually for the map's key. This is the same data that is used behind-the-scenes when you call game.add.tilemap(key).

function create() {

    // get the asset key for this level
    mapKey = "key-for-this-level";

    // pull the tilemap data from the asset cache
    var tilemapData = game.cache.getTilemapData(mapKey);

    // all the data from Tiled is in the data field
    var mapData =;

    // set the stage's background color from the map's background color.
    // note that Tiled didn't capitalize the "c"...
    game.stage.backgroundColor = mapData.backgroundcolor;

    // go about making the make the normal way
    var map = game.add.tilemap(mapKey);
    map.addTilesetImage("ground", "tiles");

    // ... the rest of the stuff ...


The tilemap data object returned from the asset cache has itself a data field, which is essentially the Tiled JSON map object. The backgroundcolor property is there can can be used to set the backgroundColor property for the stage. Remember, you can view the full source code to this game in its public repo on GitHub!

It really was that simple. In only a few minutes, I feel like I accomplished something on this game for the first time in a month! It doesn't take much to make me feel good about my achievements. Now, go read today's comic and feel good about that achievement! comic for 13 April 2016