I'm working on a game idea (2D) that needs directional lights. Basically I want to add light sources that can be moved and the light rays interact with the other bodies on the scene.

What I'm doing right now is some test where using sensors (box2d) and ccDrawLine I could achieve something similar to what I want. Basically I send a bunch of sensors from certain point and with raycast detect collisions, get the end points and draw lines over the sensors.

Just want to get some opinions if this is a good way of doing this or is other better options to build something like this?

Also I would like to know how to make a light effect over this area (sensors area) to provide a better looking light effect. Any ideas?

  • \$\begingroup\$ What do you mean by light rays? Are they distinctive objects or just same old light? \$\endgroup\$ – snake5 Oct 19 '12 at 12:08
  • \$\begingroup\$ @snake5 same old light \$\endgroup\$ – Sebastián Castro Oct 19 '12 at 12:25

The better way would be to generate and render shadow volumes. The algorithm itself is too complex to correctly describe it from memory but the idea itself, at least for directional lights, is quite simple. Since you're using Box2D, I'll assume you have convex polygons everywhere prepared.

Shadow volume polygon generation:

For each edge, check dot(edge normal, light direction) to know if edge is lit or in shadow. Remember the same value of the previous edge. There are 4 cases to process from here:

  • Current edge (CE) is lit, previous edge (PE) is lit: just add second vertex
  • CE in shadow, PE in shadow: add second vertex + offset (light direction * big number)
  • CE in shadow, PE is lit: add first vertex + offset, add second vertex + offset
  • CE is lit, PE in shadow: add first vertex, add second vertex

This shadow volume will include the polygon itself so as to avoid making it appear lit. It is also convex so there should be no problems rendering it.

Rendering: for each light, clear shadow buffer, draw all volumes to buffer, use the buffer to draw the light.

The buffer can be a z-buffer or a stencil buffer (creates pixel-perfect shadows) but it can also be a shadowmap, though in that case you'll also have to use the stencil to prevent the solid polygon from appearing lit.

| improve this answer | |

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.