- Home /
Is it possible to obscure 2D objects behind a transparent mesh?
Is it possible to create a transparent mesh where everything behind it or overlapping it becomes invisible? I still would like the portions of the objects which are not behind the mesh to be visible.
For context, I want to have the ability to create dynamic barriers between two different versions of the level in a 2D game which the player can then travel between. I figure that one implementation of this would be to have two cameras pointed at two different versions of the level, and when a barrier is created have the two cameras overlapping with each respective side of the barrier on each camera turned invisible. Lol does that even make sense? Is there a better way of accomplishing this effect? Thanks in advance.
Answer by A_Lego · Nov 08, 2021 at 12:45 PM
Just an idea(I don't really use 2D too often), but I believe you could use a sprite mask on the barriers. But they do the opposite by only showing things. An alternative could be to use a UI Mask. Unity has more information on the UI Mask in it's documentation.
Hey, thanks for your reply! I'm not sure that a UI Mask would work. I need to be able to make multiple masks and they have to be triangular as there will be up to 3 boundaries displayed at a time and they can be horizontal, vertical, or on a 45-degree angle. I'll attach a picture that I made to help illustrate the idea better.
Answer by VitoIaquinta · Nov 28, 2021 at 06:32 AM
Just in case anyone that was following this still needs help with it. You can achieve this effect with a custom shader on a custom material on the mesh. The custom material part is easy. Just create a custom material in your assets and attach that to your mesh. Then create a custom shader for this new material that you've made with the following code:
Shader "Custom/InvisibleMask"
{
SubShader
{
Tags { "Queue"="Geometry-1" }
Pass
{
Blend Zero One
Cull Off
}
}
}
Now whenever a mesh with this material sits in between your camera and your scene, any portions of sprites that sit behind it won't be visible to the camera, and the background will render to the camera instead.
Note: the "Blend Zero One" line is what makes it a transparent occluder, and the "Cull Off" makes it render to both sides. So it will still work with only the former, but only in one direction. This should work and be less costly if your meshes are always facing the same way. Mine were being generate programmatically, so their rotation was sometimes flipped, and as a result I had to make them double-sided.