首先定义一个裁剪范围,
_DisappearOffset("offset",Range(-1,1)) = 1
在顶点着色器中,取某个轴的值与裁剪的数相减存储在UV的z分量中
v2f vert (appdata v){v2f o;o.pos = UnityObjectToClipPos(v.pos);o.uv.xy = v.uv;o.uv.z = _DisappearOffset + v.pos.z;return o;}
在片元着色器中返回uv.z的数值,查看值
fixed4 frag (v2f i) : SV_Target{ return i.uv.z;}
在片元着色器中使用Clip函数,将小于0的位置裁剪掉
fixed4 frag (v2f i) : SV_Target{ clip(i.uv.z);fixed4 col = tex2D(_MainTex, i.uv);return col;}
Clip函数的实现如下:
如果x<0则裁剪掉此片断
void clip(float4 x)
{if (any(x < 0))discard;
}
最终效果:
代码:
Shader "Custom/ClipShader"
{Properties{_MainTex ("Texture", 2D) = "white" {}_DisappearOffset("offset",Range(-1,1)) = 1}SubShader{Tags { "RenderType"="Opaque" "RenderQueue"="Geometry"}LOD 100Pass{CGPROGRAM#pragma vertex vert#pragma fragment fragstruct appdata{float4 vertics : POSITION;float2 uv : TEXCOORD0;};struct v2f{float3 uv : TEXCOORD0;float4 vertics : SV_POSITION;};sampler2D _MainTex;float4 _MainTex_ST;float _DisappearOffset;v2f vert (appdata v){v2f o;o.vertics = UnityObjectToClipPos(v.vertics);o.uv.xy = v.uv;o.uv.z = _DisappearOffset + v.vertics.z;return o;}fixed4 frag (v2f i) : SV_Target{ clip(i.uv.z);// sample the texturefixed4 col = tex2D(_MainTex, i.uv);return i.uv.z;}ENDCG}}
}