Objects and Layered rendering

Modifying existing code

We'll modify some object types and code we've created in previous lessons to accomodate our lessons. Firstly, we'll add an object property to the Tile class:

	this.object	= null;

To our TileMap object, we'll add a levels property, which will specify how many different layers we'll be drawing objects and tiles to. For now, we'll hard-code this as 4. This means we'll have layers 0 to 3. Floor tiles will be drawn on layer 0, the bottom-most layer.

	this.levels	= 4;

Blocking Character movement

We'll also update the Character.canMoveTo method to accomodate impassable objects. Before we return true from this method, but after we've completed the other checks, we'll look and see if the target tile has an object. If so, we'll see if the objectTypes entry for this object's collision is solid (objectCollision.solid). If so, the character cannot move here and we can return false.

	if(mapTileData.map[toIndex(x,y)].object!=null)
	{
		var o = mapTileData.map[toIndex(x,y)].object;
		if(objectTypes[o.type].collision==objectCollision.solid)
		{
			return false;
		}
	}

Adding example objects

We can now add some example objects to our map in the window.onload method. Somewhere after we've called the buildMapFromData method, we'll create a bunch of example objects - I won't go in to detail on this, as it should be reasonably self-evident what's begin done. Suffice to say, we create our object instances then placeAt where we want them on the map.

	var mo1 = new MapObject(1); mo1.placeAt(2, 4);
	var mo2 = new MapObject(2); mo2.placeAt(2, 3);
	
	var mo11 = new MapObject(1); mo11.placeAt(6, 4);
	var mo12 = new MapObject(2); mo12.placeAt(7, 4);
	
	var mo4 = new MapObject(3); mo4.placeAt(4, 5);
	var mo5 = new MapObject(3); mo5.placeAt(4, 8);
	var mo6 = new MapObject(3); mo6.placeAt(4, 11);
	
	var mo7 = new MapObject(3); mo7.placeAt(2, 6);
	var mo8 = new MapObject(3); mo8.placeAt(2, 9);
	var mo9 = new MapObject(3); mo9.placeAt(2, 12);
Page loaded in 0.014 second(s).