Tilemap bitmasking

Tilemap bitmasking

As a game developer, bitmasks are useful when it comes to representing a set of data with single digit in both 3d and 2d games. An illustration of this in use in three dimensions can be found within the well known voxel game minecraft. The current status of a block may be represented with a bitmask value to indicate whether it is open or closed when considering blocks adjacent to it. For a given voxel if one (or however many) side(s) is open but surrounding sides closed, perhaps you wish to show a grass texture or only render one side – that voxel would have a bitmask value based on what surrounds it and we can use that to determine how it should render.  If the voxel is completely surrounded, it has a different bitmask value and perhaps you wish not to even render voxels with a bitmask value that indicates it should not be visible. In this usage scenario, what this bitmask value tells you is whether the voxels on each side are open or closed – and this is all saved with a single bit. In other words, through a single bit you are storing a set of data that would otherwise require more memory!

In a 2d game this has all sorts of usage scenario’s too. For example, when it comes to tilemaps and placing tiles there is a huge benefit to storing data represented as a bitmask value. For example, a fence – having a single fence tile may have a stand alone sprite to display, however, placing two fence pieces beside each other may require two different tiles drawn to line up. This means that an algorithm will have to determine the surrounding sides to decide which fence piece should be rendered (i.e. an end piece, middle piece, L shape, etc). We can use a simple calculation to determine this for a 2d tilemap:

With this simple equation, we will then know which tile to display. Below you can see it in action in my game Attack of the Dead – I’ve replaced the wall tiles with some dummy tiles to show the bitmask value for illustration. The variables left, down, right, and up are simple boolean values to indicate whether there is a tile at these positions surrounding the tile you are calculating for.

The textures to display the tile may be named according to the bitmask value for easy organization, or alternatively, you may assign a tile to display based on the bitmask value of that tile and organize your atlas based on the bitmask value.

If you need a quick 4 tile bitmask chart, I’ve thrown one together on JSFiddle below. You can easily modify this for using 8 tiles or whatever suits your needs.

Comments are closed