Raytracing Lighting on a 2D Tilemap

Building the light map

To keep track of lighting throughout the map, we'll create some global variables. First, there will be lightMap, that stores the light levels over ever map tile, and allLights, an array that will contain each light object on our map.

We'll also create a baseLighting variable, which will store the minimum light level for each tile. This is because in our example we want all the map to be visible to some degree - if we wanted unlit areas to be completely invisible (blacked out), we could just set the value of this variable to 0.

var lightMap = null;
var allLights = [];

// The minimum lighting for the map
var baseLighting = 0.1;

Rebuilding the light map

Before we begin drawing our map, or when we update any lights on the map, we need to call our rebuildLightMap function to recreate the lightMap array. This function begins by resetting the lightMap global to an empty array, and then fills it to the same length as our mapData array with the lowest possible light level, baseLighting:

function rebuildLightMap()
{
	lightMap = new Array();
	for(var i = 0; i < (mapW*mapH); i++) { lightMap[i] = baseLighting; }

Now we can loop through all of the lights in the allLights array, and for each light loop through its lit area property to find all the tiles touched by this light.

	for(var l in allLights)
	{
		for(var a in allLights[l].area)
		{

Finally, we check if the illumination provided by the current light source at the destination tile is more than the current illumination value for the tile (provided either by the baseLighting value, or another light). If it is, we set the lightMap value to the value provided by this light:

			if(lightMap[a] < allLights[l].area[a])
			{
				lightMap[a] = allLights[l].area[a];
			}

Now we just need to go ahead and close the open loops and this function with three curly braces:

		}
	}
}
Page loaded in 0.011 second(s).