Is there a way to know how far away is any object behind a transparent object in shader? Like making water fully transparent when close to shore.


2 Answers 2


Yes, absolutely. The method is outlined in this presentation from Unity in 2011. (See the section "Soft Particles" on slide 22)

Some of the shader conventions have changed since then, but the core principles remain the same.

Add a Sampler2D to your shader called _CameraDepthTexture to read the depth buffer (if you're using deferred rendering, this is effectively free. In forward rendering, it may generate a separate depth-only pass in some situations/platforms where the depth buffer can't be directly sampled)

To sample it, work out the position of the current fragment being drawn to the screen (using VPOS is probably the simplest way if you're using Shader Model 3.0 or higher - see this answer for an example - otherwise you can pass your projected position from the vertex shader and divide by w in the fragment shader)... and then convert that to a uv coordinate in the range 0-1.

Then use this screenUV to sample your depth buffer using, eg.

float backgroundDepth = 
             tex2D(_CameraDepthTexture, screenUV)

All those wrappers are Unity macros/built-in methods to help decode the depth from whatever format Unity is using on the current platform, and get it into worldspace units.

Now you can compare this to the worldspace depth of your fragment (interpolated from each vertex) to get your blending factor.


You need rendered depth buffer for this to work. First you would get the current fragment depth, and then read the depth buffer value on that fragment and then calculate the transparency value for the fragment based on the difference of the two depth values. Check documentation for the depth buffer.


You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .