Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.
  2. We have updated the language to the Editor Terms based on feedback from our employees and community. Learn more.
    Dismiss Notice

Need help to create a FogOfWar/FieldOfView shader using stencil and/or postprocessing

Discussion in 'General Graphics' started by OldHarryMTX, Mar 18, 2020.

  1. OldHarryMTX

    OldHarryMTX

    Joined:
    Sep 18, 2018
    Posts:
    45
    Hi all
    I am trying to create a graphic effect that simulates a Fog Of War or a Field Of View. As you can see from the image I create a mesh (purple) through a script that represents the Field Of View of the unit.


    (The image was taken from above in an orthogonal view but the game will be in perspective with a free camera)

    I want the portion of the map covered by the mesh to be in color, while the rest in black and white.

    I have highlighted two possible solutions:
    1. Using a Stencil Shader I can easily show the part of the map overlapped by the mesh, but the rest is invisible to me. Is there any way to show both map portions covered and uncovered by a stencil and applying two effects to each (RGB and BW)?
    2. By creating a mask (via Graphic.blit?) To be used with a postprocess shader. In this case, however, I was unable to find a way to Blit a Render Texture that, for example, has white pixels everywhere except in correspondence of the mesh, and then use that as a mask in a custom shader to apply the two effects. All this with the purple mesh invisible in the final result!
    Of the two I prefer the first way, but I don't know if it is viable.

    Consider that, in the end, there may be multiple meshes simultaneously to "illuminate" the area.

    Maybe I'm getting lost and in reality it is simpler than it seems, but I would need your help to get to a solution.

    Thanks in advance
     
    Last edited: Mar 18, 2020
  2. OldHarryMTX

    OldHarryMTX

    Joined:
    Sep 18, 2018
    Posts:
    45
    I think I have come up with a solution.
    1. I have excluded the Field Of View layer from the culling of the main camera.
    2. I created a second camera, attached to the main one, which sees only that layer and points to a RenderTexture.
    3. I created a postprocess shader that uses that RenderTexture as a mask to apply the effect to the main camera.
    4. Profit.
    The result is exactly what I wanted, although I hoped not to have to use two cameras.

    Is this a good solution for you?

    Thank you in advance
     
    Last edited: Mar 18, 2020
  3. faolad

    faolad

    Joined:
    Jan 27, 2013
    Posts:
    118
    Hello, I saw this and try to replicate without success on URP. Any thoughts?