2010 June


2D Lightning Continued

By | Blog, Featured, XNA Games | 33 Comments

A week ago i received a twitter message about the 2d lightning i posted. He asked me there if i could reproduce some normal mapping effect with correct lightning. I failed in doing so with the previous code i posted, so i picked it up and began coding once again om my lightning. The results where very pleasing for me and the person that asked for it :).

The results ended up like this:

The effect can off course better be viewed in motion, so i created a little movie for you as wel:

See it in HD on youtube

Source Code

Now it is time for some code, i will not discuss all the code that is required for this effect because at the bottom of the page you can also download the sample code that contains everything you saw in the movie.

First of all you will require a color map of your current scene and a normal map (in the sample we only use one texture for this)

Together with a light source these two images become the result you see below (this image has a low ambient light):

The color map and normal map texture will both be rendered to their own rendertarget. This will result into two different textures, one is your color image and one your normals. These two textures are provided to the shader effect as parameters to create a light map, such image you can see below. This is where all the magic happens :).

This lightning texture is then combined with the color map to produce the desired effect. I do it this way because i had some problems before rendering multiple lights, doing it this way i didn’t have any of those problems.

The variables or constants inside the shader effect file (MultiTarget.fx) can be tweaked to your desires. Especially the following line will adjust the specular highlight (or you can disable it this way):

Also the height of the light will have a huge impact on how the coloring will react. The default value of the height of the light will be around 100. Try to lower the number and see what it does :).

If you have any questions remaining, feel free to ask me :).

Update: I updated the sample application to work with xna 4.0. The lights are now working with a generic list; A specular strength variable is used; Shader is slightly modified.
LightningSample-XNA-4.0 (1541) (This requires XNA 4.0 installed)