Shader-透明效果-透明度测试

深度缓冲:

渲染每个物体,会将深度值写入深度缓冲。

ZWrite:

Controls whether pixels from this object are written to the depth buffer(default is On).

ZTest:

How should depth testing be performed. Default is LEqual (draw objects in from or at the distance as existing objects; hide objects behind them).

一个片元透明度符合条件(透明度小于某个阈值),直接被舍弃。否则就会按照普通的片元进行深度测试、深度写入等。因此我们不需要关闭深度写入。
我们在片元着色器中使用clip函数进行透明度测试

Shader "Unlit/AlphaTest"
{
    Properties{
        _Color("Main Color",Color) = (1,1,1,1)
        _MainTex("Main Tex", 2D) = "white"{}
        _Cutoff("Alpha Cut off", Range(0,1)) = 0.5
    }
        SubShader{
            Tags{"Queue" = "AlphaTest" "IgnoreProjector" = "True" "RenderType" = "TransparentCutout"}
            Pass{
                Tags{"LightMode" = "ForwardBase"}
                CGPROGRAM
                #pragma vertex vert
                #pragma fragment frag
                #include "Lighting.cginc"

                fixed4 _Color;
                sampler2D _MainTex;
                float4 _MainTex_ST;
                fixed _Cutoff;

                struct a2v {
                    float4 vertex : POSITION;
                    fixed3 normal : NORMAL;
                    float4 texcoord : TEXCOORD0;
                };

                struct v2f {
                    float4 pos : SV_POSITION;
                    float3 worldNormal : TEXCOORD0;
                    float3 worldPos : TEXCOORD1;
                    float2 uv : TEXCOORD2;

                };

                v2f vert(a2v v){
                    v2f o;
                    o.pos = UnityObjectToClipPos(v.vertex);
                    o.worldNormal = UnityObjectToWorldNormal(v.normal);
                    o.worldPos = mul(unity_ObjectToWorld, v.vertex);
                    
                    o.uv = TRANSFORM_TEX(v.texcoord, _MainTex);
                    return o;
            
                }
                fixed4 frag(v2f i) :SV_Target{
                    fixed3 worldNormal = normalize(i.worldNormal);
                    fixed3 worldLightDir = normalize(UnityWorldSpaceLightDir(i.worldPos));
                    fixed4 texColor = tex2D(_MainTex, i.uv);
                    clip(texColor.a - _Cutoff);

                    fixed3 albedo = texColor.rgb * _Color.rgb;
                    fixed3 diffuse = _LightColor0 * albedo * max(0, dot(worldNormal, worldLightDir));
                    fixed3 ambient = UNITY_LIGHTMODEL_AMBIENT * albedo;
                    
                    return fixed4(diffuse + ambient, 1.0);
                }
                ENDCG
            }
        }
}
Shader-透明效果-透明度测试_第1张图片
Cutoff 0

将Cutoff的值设置为0.65,图中透明度在0.65以下的直接被舍弃了


Shader-透明效果-透明度测试_第2张图片
Cutoff 0.65
Pass{
                Tags{"LightMode" = "ForwardBase"}

                Cull Off

在代码中添加Cull Off关闭渲染图元的剔除功能,这时所有的物体都是正反面双向渲染,得到效果如下


Shader-透明效果-透明度测试_第3张图片
AlphaTestCullOff.PNG

你可能感兴趣的:(Shader-透明效果-透明度测试)