4、shader透明测试(AlphaTest)

主要用于花草树木

用3D的Plane来实现透明的例子:

给Plane先赋予一个带alpha通道的透明图片,但是此图片此时是看不出来是透明的,如下:

现在我们要做的就是显示透明的效果:现在就用到了alphatest了,

表面着色器实现代码:

Shader "Custom/Plane" {
    Properties {
        _MainTex ("Base (RGB)", 2D) = "white" {}
        _alphaValue("alphavalue",range(0,1))=0.3
    }
    SubShader {
        Tags { "Queue"="Transparent" "RenderType"="Transparent" }
        LOD 200
        alphatest greater [_alphaValue]
        
        CGPROGRAM
        #pragma surface surf Lambert

        sampler2D _MainTex;

        struct Input {
            float2 uv_MainTex;
        };

        void surf (Input IN, inout SurfaceOutput o) {
            half4 c = tex2D (_MainTex, IN.uv_MainTex);
            o.Albedo = c.rgb;
            o.Alpha = c.a;
        }
        ENDCG
    } 
    FallBack "Diffuse"
}

顶点片段着色器实现代码:

Shader "Custom/testalphatest" {
    Properties {
        _Color("Base COlor",Color)=(1,1,1,1)
        _MainTex ("Base (RGB)", 2D) = "white" {}
        _alphaValue("alphavalue",range(0,1))=0.5
    }
    SubShader {
        Tags { "queue"="transparent" "RenderType"="Transparent" }
        LOD 200

        
        Pass
        {
        alphatest greater [_alphaValue]
        Name "simple"
        Cull off
        CGPROGRAM
        #pragma vertex vert
        #pragma fragment frag
        #include "UnityCG.cginc"
        float4 _Color;
        sampler2D _MainTex;

        struct v2f
        {
            float4 pos:POSITION;
            float4 uv:TEXCOORD0;
        };

        v2f vert(appdata_base v)
        {
            v2f o;
            o.pos=mul(UNITY_MATRIX_MVP,v.vertex);
            o.uv=v.texcoord;
            return o;
        }

        half4 frag(v2f i):color
        {
          float2 uv=i.uv.xy;
          half4 c=tex2D(_MainTex,uv)*_Color;
          return c;
        }

        
        ENDCG
        } 
    }
}

还有一个步骤就是:在Unity的PC平台下的Play settings下,把Use Direct3D 11*给关闭了就可以了!有可能是dx11不支持alphatest的缘故吧!

最终效果:

对象为cube时的效果:

调整为less时,显示的效果

原文地址:https://www.cnblogs.com/MrZivChu/p/shader4.html