Tuesday, July 5, 2011

XNA 2D Dynamic Lighting

I've been recently tossing around the idea of making a game with XNA 4.0. One feature I really wanted was the ability to move between night and day and have darkness in caves, etc. Having never messed with shaders before I spent a good amount of time playing with HLSL and learned how to do the effect apparently known as "fog of war."
While researching this technique I ran across many people asking for help with this and most of the help was pointing to broken links or deprecated information. While I make no claims about the quality of the code I do imagine that this will be useful to someone searching for this technique.
If you're just looking to get your feet wet you can download a working demo here.
The following images were used to render the scene:

Background courtesy of Open Game Art
This scene without any effects applied.

The lighting mask dynamically created with additive blending.

The final rendered scene.

Video Example:

7 comments:

  1. Thats what i'm looking for ... thanks a lot.

    ReplyDelete
  2. Thats what i was looking for too.... but when i tryed to run the sample... i'm getting this error message:

    XNA Framework Reach profile requires TextureAddressMode to be Clamp when using texture sizes that are not powers of two.

    at line 140 in LightingDemo.cs

    spriteBatch.Draw(mainScene, new Vector2(0, 0), Color.White);

    Can you help me? what i'm doing wrong?
    my e-mail is gustavo@ushijima.com.br

    thanks a lot!!!

    ReplyDelete
  3. @Anonymous, To get rid of the Clamp error:
    Paste this line of code inside the initialize method:

    ---
    GraphicsDevice.SamplerStates[1] = SamplerState.LinearClamp;
    ---

    ReplyDelete
  4. Very nice example, I was able to adapt it in one of the games I'm working on. My question is, how would I go about drawing something on top of the darkness? I want to draw a HUD but it is being affected by the dark.

    ReplyDelete
    Replies
    1. I believe you have to call two different Begin chunks. One for the lighting and the background, and then another for the HUD that isnt affected by the lighting

      Delete
  5. Good work :)
    But i have a question.
    How can i run this in XNA 3.1?
    This example is exactly that i want but all my project runs in 3.1, i search a lot and couldn't found this in 3.1 :/

    ReplyDelete
  6. Many many many thanks!! Perfect!

    ReplyDelete