Raytracing Lighting on a 2D Tilemap

Placing random lights

Just out of curiousity's sake, lets look at how we generate the random lights. In your game, you'd most likely want to place the lights in specific locations, so you can skip over this if you feel with how new light objects are created.

We'll call the function resetLights, and begin by clearing the allLights array.

function resetLights()
{
	// Remove existing lights
	allLights.length = 0;

We'll tell the code to execute until we've created 5 random lights:

	while(allLights.length < 5)
	{

The Javascript Math.random method returns a random floating point number between 0 and 1. We'll use this plus 0.3 for the lights intensity.

		var intensity = 0.3+Math.random();

For our radius, we'll just make it that the brighter the lighter, the further we want it to shine. Our lights radius (in tiles) will be the intensity we randomly generated divided by 0.05, rounded down to the nearest whole number.

		var radius = Math.floor(intensity / 0.05);

The lights position, will just be a random coordinate that falls within the maps bounds (between 0 and mapW or mapH depending on whether we're creating the x or y coordinate).

		var x = Math.floor(Math.random()*mapW);
		var y = Math.floor(Math.random()*mapH);

Now we check if the random x, y coordinate we've chosen falls on a solid tile (a 0 in the mapData array); if it does, we create another random light by jumping back to the start of the loop and try again:

		if(mapData[((y*mapW)+x)]==0) { continue; }

We'll now create a temporary placeHere boolean variable, and loop through and other lights we've already created in the allLights array. If any other lights already occupy the random x, y position we've chosen, we jump back to create a new random light.

		placeHere = true;
		
		for(l in allLights)
		{
			if(allLights[l].position[0]==x &&
				allLights[l].position[1]==y)
			{
				placeHere = false;
				break;
			}
		}
		
		if(!placeHere) { continue; }

If our collision checks are passed, we create a new Light object with the random parameters, calculate the area it illuminates with its method, and add it to the allLights array.

		var l = new Light(x, y, radius, intensity);
		l.calculate();

		allLights.push(l);

We can now close the random light generation loop. When the loop is completed, we'll rebuild our light map (rebuildLightMap), and we're done!

		}

	rebuildLightMap();
}
Page loaded in 0.01 second(s).