例如剔除掉船超出河流的一部分,實現讓船只在河流之上顯示。

其實是利用UI層的Mask實現遮罩,有些不同的是Mask的圖片是用Camera渲染到RenderTexture動態產生的紋理實現的。
大概步驟如下:
1 分層渲染,建立Mask蒙版層。
2 河流設置為Mask層。
3 建立Mask Camera,只渲染Mask蒙版層
4 創建腳本MatchScreenRenderTexture,創建與窗口匹配的RenderTexture,令Mask Camera渲染到該RenderTexture中。
5 創建腳本MaskScript,建立一個MaskShader(類似於全屏特效),令MaskCamera渲染的顏色部分背景部分透明變成不透明,即反轉Alpha。
6 建立UI Image。設置Image為窗口大小,設置使用MatchScreenRenderTexture中的蒙版紋理。
7 添加Mask組件,令Image遮罩住船精靈的部分。
1 Shader "Tracy/MaskShader" {
2 Properties{
3 _MainTex("Base (RGB)", 2D) = "" {}
4 _Background("Background Texture",2D) = ""{}
5 }
6
7 // Shader code pasted into all further CGPROGRAM blocks
8 CGINCLUDE
9
10 #include "UnityCG.cginc"
11
12 struct v2f {
13 float4 pos : SV_POSITION;
14 float2 uv : TEXCOORD0;
15 };
16
17 sampler2D _MainTex;//攝像機的輸出畫面作為紋理
18 sampler2D _Background;//背景
19 sampler2D_float _CameraDepthTexture;//沒用,修改自StandardAsset的imageeffect
20
21 v2f vert(appdata_img v)
22 {
23 v2f o;
24 o.pos = mul(UNITY_MATRIX_MVP, v.vertex);
25 o.uv = v.texcoord.xy;
26 return o;
27 }
28
29 float4 frag(v2f i) : SV_Target
30 {
31 //float d = SAMPLE_DEPTH_TEXTURE(_CameraDepthTexture, i.uv.xy);
32 //d = Linear01Depth(d);
33 float4 c = tex2D(_MainTex, i.uv.xy);
34 float4 cbg = tex2D(_Background, i.uv.xy);
35 return float4(cbg.r, cbg.g, cbg.b, 1 - c.a);//翻轉alpha
36 }
37
38 ENDCG
39
40 Subshader {
41
42 Pass{
43 ZTest Always Cull Off ZWrite Off
44
45 CGPROGRAM
46 #pragma vertex vert
47 #pragma fragment frag
48 ENDCG
49 }
50 }
51
52 Fallback off
53
54 } // shader