Build a Dynamic Texture Atlas in Phaser

Thursday 29 January 2015

Our game will have 8 teams, each with their own colored uniforms.  Well it would be confusing if they didn't, wouldn't it?

Umm, friend or foe?


If there are 8 different unit types, each with their own animation frames, that makes hundreds of little sprites to manage.  Now, what if the artist wants to give the soldier a backpack?  Do you see the problem?


No fair, we want backpacks too!

To maintain the artist's sanity, our goal is to only create one texture atlas for one team and dynamically create sprites for the rest of  the teams.  One solution could be Phaser's Sprite.tint()



Its quick and easy, but does not always give the best results.

Are you feeling okay?

No, what we need is some kind of pixel switching.  The artist has already created a palette for the team colors that was being used while creating the sprites.  Lets grab those colors by including the palette in our texture atlas.



We then load it into a BitmapData object so that we can read out the colors.



You can see that we have loaded the texture atlas definition into a global game information variable, g_game.spriteAtlas.

Now we want to grab each color in the palette and put them into a color lookup variable.  Our palette is made of 4x6 pixel squares and the colors I am interested in are in columns 1-7.



Now we have our handy color lookup and we need to apply it to the original sprites.  First, we will create another BitmapData which will become our new texture atlas.  We also define a new atlas definition file so Phaser will know how to find all of the new sprites.



 And finally build our new texture atlas by copying the original sprite onto it and then switching the pixels using our color lookup.



One last update() to make sure all changes are applied to the BitmapData object, then add the new texture atlas into Phaser's cache.



Now we are ready to create sprites using our new texture atlas!



That's all for now!





 






4 comments:

  1. Was looking for something to dynamically generate texture atlases for use in buttons that are dynamically resized using Nine slice/patch images. This will come in handy, thanks.

    ReplyDelete
  2. Beautiful remedy. Swapping out specific colours instead of creating a new Spritesheet on the fly! What will they think of next, haha.
    Thanks for this.

    ReplyDelete