- Home /
Render 2d lights by subtracting them form base layer (similar to vision cones)
Hey everybody,
In my game a want to archive a similar light (visibility) effect to the game door kickers (See example image: https://steamcdn-a.akamaihd.net/steam/apps/248610/ss_7dc9becbb070fe26b7e9b13742ea25f79737b7bd.1920x1080.jpg?t=1580479475)
As you can see, when there is no light (or in the case of door kickers the vision cone) the game overlays the map with a gray alpha map and subtracts the light cones form it.
The light code I set up so far does all visibility calculations and returns the light area as an array of points (the vertices of the shape) which are sorted clockwise. My question now is: What would be the best way of creating this effect? I thought about using a shader, but couldn't find anything promising so far. Another idea was using one base mesh and subtracting meshes that describe the lights from it, but this seemed very complicated for such a simple effect to me.
Important information:
The light shapes can be concave The lights can update during gameplay, so
the calculation must be fast enough
to be executed every frame.The new Freeform Light2D in the Universal Render Pipeline is not an option, as the code for the 2D light isn't set up for these kind of realtime effects
Any ideas or hints in the right direction would be greatly appreciated.
(Note: When I speak of lights, I mean my own code, I don't use any 2d Lights or other lights in my 2D game)
Answer by Simulacr0n · Feb 11, 2020 at 07:33 PM
For anyone having similar problems in the future:
I solved this problems by creating two shaders that use the stencil buffer. The light writes into the stencil buffer at the area it fills and a mask that overlays the complete level only renders the areas, where the stencil buffer doesn't contain the value of the light mask. To get to this solution I used this excellent Tutorial by Sebastian Lague: https://www.youtube.com/watch?v=xkcCWqifT9M (However I modified the shader a bit, because I don't want objects to disappear completely) Also helpful: https://www.ronja-tutorials.com/2018/08/18/stencil-buffers.html The Unity manual also helps understand lots of commands that the stencil buffer uses: https://docs.unity3d.com/Manual/SL-Stencil.html
Your answer
Follow this Question
Related Questions
Shader not whiter than the original sprite color? 0 Answers
Trying to create 2D pixel art lighting 1 Answer
Unity 2D blur lit shader 0 Answers
Light of Sight - 2D Dynamic Lighting (Field of View) 0 Answers
2d lighting effect 1 Answer