Custom 2D Lighting System in Unity

664 Views Asked by At

Ok so I've been trying to make a custom 2D lighting system in Unity, and I'm at that annoying stage where I know what I want to do but I'm not sure how to do it.

Here's the plan:

  1. There will be dedicated light objects with their own meshes. These meshes determine the shape of the light.
  2. Before the camera renders the whole scene, it does an extra render of just the light meshes with a black background to create a lightmap.
  3. Then the camera renders the scene as normal (does NOT render the light meshes this time). Every object has a shader that will access the lightmap and shade itself appropriately depending on the color of the lightmap at that point.

That's the idea anyway. I sorta threw together a botched form of this. I used a separate camera to render the lightmap into a render texture with a culling mask so that it only rendered the light meshes, which are on their own layer. I then manually passed that texture to the shaders which use their screen uvs to sample from it.

This works sorta ok, but the scene view is completely messed up since it tries to light things as if you were looking at it from the perspective of the lighting camera. I feel like this would make the system hard to use, so I want to try to make some that feels a bit more cohesive.

Here's some screenshots to explain: Scene Setup. The tan-ish box is my "light," which gets rendered to the light cam, visible in scene. This next shot is what renders to the lightmap: Lightmap render The black background is not from the big black box, the clear flag is just set to Black.

Now according to this lightmap, the middle of the screen should be lit up. and that's exactly what happens:bad lighting

Notice that in the game view, since the light camera is set up with the same position/rotation/perspective settings as the game camera, it looks fine: Game view

The main problem is figuring out that extra render. Is there anyway to create an extra pass for the main camera before the scene render that only renders the light meshes? I could probably figure out the rest from there. It would also be nice if I could make the lightmap a global shader variable, that way I don't have to pass it to each individual material, but one thing at a time, right?

Thanks so much to anyone who can shed some light on this subject. I'm still pretty new to shaders and rendering, so any help is much appreciated.

1

There are 1 best solutions below

1
Yuris On

If I understand correctly, your problem is the appearance of your lights in Scene View, right ?

For that, you can create a custom Gizmos for them and hide the original objects. There's a tutorial:

https://learn.unity.com/tutorial/creating-custom-gizmos-for-development-2019-2#5fa30655edbc2a002192105c