lekoman
lekoman

Reputation: 31

Using a sprite to mask 3D objects in Unity

I have a png image that I want to work as a transparent mask, where it will be completely transparent in the scene but 3D objects behind it would not be shown (similar to a sprite mask, but needs to work with 3D objects).

So I added the image as a sprite (point - no filter) in my 3D scene and I have a shader already applied to the sprite material, but it is not working properly. Looks like the pixels are not being "cut correctly" in the borders.

I'm using this approach since the unity built-in "2D sprite mask" only affects objects using Sprite Renderer (as explained here https://docs.unity3d.com/Manual/class-SpriteMask.html), but I want it to affect 3D objects.

So this is the shader:

    Shader "Masked/Mask" {
 
     SubShader {
         Tags {"Queue" = "Geometry+10" }
         ColorMask 0
         ZWrite On
         Pass {}
     }
 }

This is the sprite to work as the mask (png image): sprite mask

And these are the result that I want vs. what Im getting: results compared

Im not good with shaders, so I would like to know if there is a change in the code that can be made in order to improve the result. I've already tried different formats for the sprite image (png, tif, compressions), but the results are the same.

Upvotes: 3

Views: 6269

Answers (1)

Immersive
Immersive

Reputation: 1704

I've done something similar using 'transparent' 3D occluders and render priorities, I imagine it would be similar with sprites...

  1. Render non-occludable geometry (including Sprite) {"Queue" = "Geometry"}
  2. Render occludable geometry {"Queue" = "Geometry+1"}

Strictly speaking, your occluder (the sprite) only needs to render to the depth (Z) buffer if it's always transparent.

Upvotes: 0

Related Questions