sample unity package
Note: this trick doesn't work with Unity SteamVR plugin's CameraRig
Note: this is a different implementation from the depth mask from unity wiki
The basic idea of depth mask is just like normal z-test. You use transparent objects (say mask objects) that are closer to the camera so other objects behind the mask objects will not pass the z-test and not be rendered.
However the problem is that under the same camera rendering, transparent objects can't be considered as passed z-test when opaque objects are behind them.
So the trick is just like the reference link above, use another camera (say camera2) that draws masked object after previous camera(say camera1) rendered the transparent masks.
In this case, camera1 draws first and makes transparent objects write to the z-buffer, then when camera2 is drawing, since the z-buffer is occupied by the transparent objects, the object behind the mask will fail the z-test.
Apparently, the camera1 and camera2 need some settings to achieve the mask effect. Just like the reference link, camera1 needs to render before camera2, so the "depth" property in Unity camera needs to be setup. Just set camera2's depth be larger than camera1's depth to achieve the rendering order.
Then since camera2 draws on top of camera1, camera2's "clear flags" needs to be set as "Don't clear".
Make sure that camera2 has exactly the same camera properties and 3D objects settings as camera1(transforms, fov...), otherwise the rendered scenes will not match.
Add transparent objects into the scene as mask. The transparent objects need to write into the z-buffer, you can use the shader code below to achieve this.
Finally, add a User Layer in Unity (say MaskedObject as the layer name), set masked object to be in the MaskedObject layer, set camera2's culling mask to MaskedObject, then try to move the masked object behind the transparent masks.
here is the result
the moving cube is masked at certain positions, those positions actually are occupied by transparent cubes and the transparent cubes occlude the masked cube.
the shader code for transparent mask object
Shader "SimpleTransparentZWrite" { SubShader { Tags{ "Queue" = "Transparent" } Pass{ Blend SrcAlpha OneMinusSrcAlpha ZTest LEqual Cull Back ZWrite On CGPROGRAM #pragma vertex vert #pragma fragment frag #include "UnityCG.cginc" struct appdata { float4 vertex : POSITION; }; struct v2f { float4 pos : SV_POSITION; }; v2f vert(appdata v) { v2f o; o.pos = UnityObjectToClipPos(v.vertex); return o; } half4 frag(v2f i) : SV_Target{ return half4(0,0,0,0.0); } ENDCG } } }
沒有留言:
張貼留言