Tile Textures


So, the way my game is setup I have tile types. Whenever I am detecting textures, I check if a tile is a certain type. For example, if(tile.getType() == Type.SOLID). But what if I wanted to have random textures for a single type. For example, decoration tiles. Alternations of a tile texture. How could I implement this without the constant updating constantly changing tile textures.


The last time I did something like that, I stored the textures within the tile instances.
Than they got a function like #draw(Map, mapX, mapY, delta, Cam); One could argue about the desing, but it offers some nice possibilitys.
Now Tiles are able to be animated, use a ‘conected texture’ system, or dont use a texture after all but just some particles maby building fog or fire or I dont know…


I have made a class called TileTextureSet. It is able to create a set of texture regions from a single image and store them in an array. I store an array of tile texture sets such as:

TileTextureSet[] floorsTTS;
floorsTTS = new TileTextureSet[2];
floorsTTS[0].frames = TileTextureSet.makeFrames(blahBlah...);
floorsTTS[1].frames = TileTextureSet.makeFrames(blahBlah...);

My tile class has:

int type, frame;

Now whenever I draw a tile i do something like:

batch.draw(floorsTTS[thisTile.type].frames[thisTile.frame], xPos, yPos);

It’s a convenient way to store all your tiles in one place, and easy to set tiles. Just set their type and frame whenever you want. There’s probably better ways to do it but using some constants to define the tile types and key frames is rather simple.

If you’re going to have a lot of tiles, having a tile instance for each position will be memory heavy. You can use LiquidNitrogen’s texture set implementation, but you can get the “frame” based on the X and Y position.

Small example:

	public static int variantNum(long magic, int x, int y) {
		return ((int) ((magic + (x + 17) * (y + 53) * 214013L + 2531011L) >> 16) & 0x7fff);

That returns a “variant number” based on the X and Y. The magic long number should be generated once on world-load.
In order to use it, you bitwise-AND it by the number of different textures you have minus one. One exception is the number of types MUST BE a power of 2 number.


						+ ((variantNum(world, x, y)) & (varianttypes - 1))), Texture.class), x
						* world.tilesizex - world.camera.camerax + offx, Main.convertY((y
						* world.tilesizey - world.camera.cameray)
						+ World.tilesizey + offy));

Examples were stolen from my other game’s code: modify as you need fit.