Wednesday, November 22, 2017

unity - How can I implement a revealing light beam?


In SEARCHLIGHT, you control a ray of light that illuminates incoming enemies that are otherwise invisible in the night sky. Here is an illustration:


Illustration


How would I go about doing this, preferably in Unity? I imagine this is less about lighting and more about shaders, but I'm not sure on details. The fact that I know very little about coding shaders makes it worse.



If it is about shaders, what are the specifics? Is there a stretched quad that moves with said shader applied to it, or perhaps is using the Line Renderer a better option?


As a beginner, may I try to achieve a similar effect, or should I leave it for when I'm better?


(P.S.: The game was made in Unity. Here is its itch.io page.)



Answer



One way to implement an effect like this is with the stencil buffer.


This is an extra few bits the renderer keeps around for every pixel in a render target, that you can use for scratch notes about what you've drawn there or are allowed to draw later.


You can create a new shader using one of Unity's built-in templates, and add some stencil operations to the top of the SubShader or Pass section:


Stencil {
Ref 1
Comp always

Pass replace
}

This says "write a 1 into the stencil buffer, no matter what was there before" - put this on the shader/material that you use to render your light beam quad, and it will mark all the on-screen pixels it's touched.


Then, for objects that should only show up inside the light beam, use:


Stencil {
Ref 1
Comp equal
}


This checks to see if the magic number 1 got written into this pixel previously (ie. is this pixel illuminated by the light beam?) - if not, the shader aborts rendering this pixel of the object, neatly clipping it to just the illuminated region of your screen.


Make sure your objects that read the stencil information render later in the queues than the objects that write it, so the information is ready for them when they look for it.


No comments:

Post a Comment

Simple past, Present perfect Past perfect

Can you tell me which form of the following sentences is the correct one please? Imagine two friends discussing the gym... I was in a good s...