先直接上结果图,未运行场景前,后面的Quad是用DepthOnly的SubCamera(depth大于MainCamera)最后渲染的,可以看到Game窗口里它无视遮挡关系渲染在最上面了:
运行场景后,我们可以看到Quad上渲染出了深度图(在Quad的shader中实现的,shader内容贴在下面).
Shader "Custom/Unlit/CameraDepth" { Properties { _MainTex ("Texture", 2D) = "white" {} } SubShader { Tags { "RenderType"="Opaque" } LOD 100 Pass { CGPROGRAM #pragma vertex vert #pragma fragment frag // make fog work #pragma multi_compile_fog #include "UnityCG.cginc" struct appdata { float4 vertex : POSITION; float2 uv : TEXCOORD0; }; struct v2f { float2 uv : TEXCOORD0; float4 vertex : SV_POSITION; float4 screenPos : TEXCOORD1; UNITY_FOG_COORDS(2) }; sampler2D _MainTex; float4 _MainTex_ST; v2f vert (appdata v) { v2f o; o.vertex = UnityObjectToClipPos(v.vertex); //float3 worldPos = mul(unity_ObjectToWorld, v.vertex).xyz; o.uv = TRANSFORM_TEX(v.uv, _MainTex); o.screenPos = ComputeScreenPos (o.vertex); UNITY_TRANSFER_FOG(o,o.vertex); return o; } sampler2D _CameraDepthTexture; fixed4 frag (v2f i) : COLOR { fixed4 col = tex2D(_MainTex, i.uv); float z = SAMPLE_DEPTH_TEXTURE(_CameraDepthTexture, i.screenPos.xy / i.screenPos.w/*这里转化为屏幕的对应坐标*/); float dist = LinearEyeDepth(z); //这两行是为了方便渲染深度图为肉眼可分辨的形式 float fact = exp(-0.1 * dist); return col * fact + fixed4(0.15, 0.12, 0.08, 0) * (1 - fact); } ENDCG } } }注意此shader中想读到_CameraDepthTexture,需要用C#代码声明下主Camera的depthTextureMode :
_camera.depthTextureMode = DepthTextureMode.Depth;
然后我们根据读到的深度图,在shader中根据深度clip一下,就相当于在fragment shader里做了个手动的z test.最后结果如下,可以看到在SubCamera中的Quad实现了与主Camera的物体的正确的遮挡关系:
(实际测试发现,被声明depthTextureMode后的Camera会把depth重画一遍导致drawcall翻倍,所以这个方法的局限性很大,故而没有继续深入研究).
运行本Demo的Unity版本为Unity2018.4.24f1.
参考资料:
https://forum.unity.com/threads/reuse-depth-buffer-of-main-camera.280460/
https://forum.unity.com/threads/cant-access-_lastcameradepthtexture-in-image-effect-shader.469780/
https://forum.unity.com/threads/using-projected-screen-space-as-texture-coordinates.431762/