2D lighting in Defold(SOLVED)

No, you don’t necessarily need a new shader for your lights. Just set the blend mode on the sprites to “Add” mode.

To draw things to a render target, first you need to create one with render.render_target() (you can copy-paste most of the parameters from the API ref or somewhere). Then, in update(), use render.enable_render_target() to enable it, and then render.clear() to clear it. After that everything you draw will be drawn to that render target, so just use render.draw() as usual. After that, call render.disable_render_target() to disable it.

That just draws stuff to the render target texture, instead of drawing things directly to the screen. So you won’t see anything yet. The next step is to add a simple quad (flat square plane) model to your scene with a material on it that mixes together both of your render target textures. You’ll want a separate predicate just for this quad so you can draw it separately. Also set the view and projection matrices so this quad fills the whole screen. In your render script you’ll need to render.enable_texture() both textures, then draw the quad, then disable both textures. For the material you need to give it a texture sampler for each render target. Then a custom fragment shader that combines them. The most basic, easy way to do it is just multiply them together. That way if the lighting texture is zero (black) you’ll just get black, and if it’s 1 (white) you’ll see the base render clearly.

To make everything black by default, just use a (0, 0, 0, 0) color to clear the lighting render target with. You can change this color to have some “ambient” lighting.

Ages ago I put up a sample project. It’s a bit old and a little bit more complicated, but maybe it will help: Link Here

2 Likes