Example of how to achieve pixel perfect shadows in a 2D view. The sample is based on the following sources:
You can use this solution in your own project by adding this this project as a Defold library dependency. Open your game.project file and in the dependencies field under project add:
https://github.com/defold/sample-lights-and-shadows/archive/master.zip
The main components of this light and shadow casting example are:
lights/lightsource.script
- Attach this script to any game object that should act as a lightsource. Modify the exposed script properties to control the light properties:
radius
[number] - Radius of the lightsource in pixelscolor
[vector4] - Color of the lightsource (RGBA)arc_angle
[number] - Arc angle of the lightsource. Can be used to generate a cone of light up to an arc angle of 180 degrees. Anything above 180 degrees will result in a full circle.static
[boolean] - Use this for static lights that do not move or rotate to skip updates of light position and rotation each frame.falloff
[number] - This controls the light intensity. With a falloff of 1.0 the light intensity gradually decreases until there is no light right at the edge. With a falloff of 2 the light intensity decreases twice as fast.enabled
[boolean] - Set to false to disable the light.lights/render/light_quad.go
- A game object with a basic model quad, used as a render target when drawing lights and shadows.lights/render/lights.render
and lights/render/lights.render_script
- The render file and render script used when drawing lights and shadows (and also all of the standard Defold components such as sprites, particles, tilemaps etc)lights/materials/light_occluder_*.material
- Materials to use for sprite, tilemaps and other components that should occlude light and cast shadows.Open game.project and scroll down to Bootstrap
and change Render file to lights/render/lights.render
. This render script works like the default render script with the addition of also drawing lights and shadows.
Add the lights/render/light_quad.go
to a collection where lights and shadows should be calculated.
Attach the lights/lightsource.script
to any game object that should act as a lightsource.
Configure the lightsource properties to your liking.
Change the material for any component that should cast shadows when lit by a lightsource. Select a material from lights/materials/
matching the component type casting shadows.
There is an example included in this repository. It sets up a few lightsources and occluders and lets you move around the scene.