Wednesday, 21 July 2010

2D Dynamic Shadow Casting (and Lighting)

After having a little think about how to do this effectively, the answer was actually rather simple (which ins't entirely in keeping with the rest of this blog).  My previous attempts involved raytracing the 2D scene. By stepping through every single point in the scene, and calculating the path to it from the light source a per pixel map of brightness can be generated. I decided however that this was far to CPU intensive for high complexity scenes so went down a simpler route. The basic algorithm was:
  • Trace a path from the light source to each vertex in each shape,
  • Continue these paths outwards from the shape, thus casting a shadow
  • Generate polygons to be filled in the shadow colour with pairs of these paths
  • Draw a light mask (just a circle with a transparency gradient over the floor)
Just click the first image to launch the experiment. I am quite pleased with the results!

The image below shows the intermediary path tracing step:

By changing the light source mask a directional torch like effect is simple to reproduce, again just click to launch the app:


  1. hi there, this is really nice, and i wonder why noone else has left any comment on this sofar. this is exactly what i want to do, in exactly the same way that i had in mind... the big difference is: you already did it. is there a chance to have a look at the sourcecode?

    kind regards

  2. looks great man! :oD any chance we could have a sniff at the sourcecode? :o)

  3. Hi guys, as soon as I get onto my home computer I will upload the source code :) Its been a busy couple of weeks!


  4. wow it realy looks good!
    I realy want to look at it.

  5. Hi, i know this is an old topic, but can you please send me the source code for his? It would be greatly appreciated :)

  6. I'd love to see the source for this (FOR LEARNING!). PM me at my gmail plox!

  7. Hey there. It's been over 2 years since you posted this, I know, but is there any chance I can have a look at that source code? I have been trying to learn how to do this all night (literally) and I couldn't figure it out. Also, as some note, I'm new to Actionscript 3, so it would be really hard to figure this stuff out. Anyways, if I could have a look at the source code, that would be great. Email me at

  8. Hi, this is a great work, please can you share this sourcecode as I am lookinh into writing a Haxe version of it for my video game thanks.