Objects and Layered rendering

Layered drawing method

We'll now modify the drawGame method - particularly the nested drawing loops. Firstly, before these loops begin we'll add an additional loop, which will iterate over our TileMap's levels.

	for(var z = 0; z < mapTileData.levels; z++)

Our code for drawing floor tiles will remain unchanged, but we'll surround it with an if statement so that floor tiles are only drawn on level 0:

			var tile = tileTypes[mapTileData.map[toIndex(x,y)].type];

			var sprite = getFrame(tile.sprite, tile.spriteDuration,
				gameTime, tile.animated);
				sprite.x, sprite.y, sprite.w, sprite.h,
				viewport.offset[0] + (x*tileW), viewport.offset[1] + (y*tileH),
				tileW, tileH);

We'll also check if there's an object on the current tile. If so, and if the corresponding objectTypes entry's zIndex is equal to the level we're currently drawing, we'll draw the sprite for this object.

			var o = mapTileData.map[toIndex(x,y)].object;
			if(o!=null && objectTypes[o.type].zIndex==z)
				var ot = objectTypes[o.type];
					ot.sprite[0].x, ot.sprite[0].y,
					ot.sprite[0].w, ot.sprite[0].h,
					viewport.offset[0] + (x*tileW) + ot.offset[0],
					viewport.offset[1] + (y*tileH) + ot.offset[1],
					ot.sprite[0].w, ot.sprite[0].h);

We also want to modify our roof drawing code a bit - the if statement, that checks if the roofType is not 0, and checks the player is not currently under the roof, will now also check that the current z loop value is 2 - this is the layer we'll draw our roofs on in our example:

			if(z==2 &&
				mapTileData.map[toIndex(x,y)].roofType!=0 &&
				mapTileData.map[toIndex(x,y)].roof!=playerRoof1 &&

Finally, after our nested y, x drawing loops, but before we end the z loop, we'll draw our player character if the current level is 1:

			var sprite = player.sprites[player.direction];
				sprite[0].x, sprite[0].y,
				sprite[0].w, sprite[0].h,
				viewport.offset[0] + player.position[0],
				viewport.offset[1] + player.position[1],
				player.dimensions[0], player.dimensions[1]);

We draw the player here so that higher level objects, such as our tree, are always drawn above the Character. Try adding some more custom objects at different levels on the map to get a good understanding of this concept!

Page loaded in 0.008 second(s).