- Home /
Creating a lighting shader
I'm trying to develop a lighting system to allow a situation where, when moving inside the outdoors appears brigher, and when moving outdoors makes the inside appear darker. The system is specifically for a 2D game.
What I have in mind currently is creating a shader that uses a float to track whether the player is indoors or outdoors, this would be adjusted by trigger colliders, and would fade from 0 when outdoors, to 1 when indoors.
I would then create a mask of a grey scale texture over the entire playable area, the textures for these would largely just be large squares of white or black, but blending in the middle from white to black for where there is a transition between indoors and outdoors, whilst the indoors and outdoors would be single quads with a 1 pixel texture, these transition sections would need to be large bespoke textures.
The greyscale texture would be present in the level over the rest of the assets, but would not technically be visible. It would use the texture as data, by using both the texture colour and the float value to track whether the player is inside or out. The shader would simply multiply the existing pixels behind the greyscale texture, by the greyscale colour + the in out value.
The logic behind this being, when the player is inside, the float InOut value is at 1, and the texture in front of him is black, therefore (0,0,0) + (1,1,1) = existing colour (1, 1, 1) so the level indoors appears at normal lighting. The outdoors however has the white texture over it, so (1,1,1) + (1,1,1) = existing colour (2, 2, 2) so the outdoors appears twice as bright. When outdoors the float value is 0, so the black pixles in front of the indoors equate to (0,0,0) + (0,0,0) = existing colour * (0,0,0) meaning darkness.
I'm not sure if my logic even works, but the shader I have written looks like this:
Everything is a fairly standard shader, other than my Blend operation is:
Blend DstColor Zero
and my fragment function is:
half4 fragmentFunction(v2f_vct i) : COLOR
{
half4 col = tex2D(_MainTex, i.texcoord) * i.color;
col = col + half4(_InOut, _InOut, _InOut, 0);
return col;
}
I've made the colour return a half4 rather than a fixed 4, because I assume that's the only way I'll be able to have the colour store 2,2,2 rather than capping at 1,1,1.
This doesn't appear to work. I'd like to know if anyone can see anything wrong with my logic or the code itself.