1. 程式人生 > >UnityShader 學習筆記 6 深度寫入的透明度混合

UnityShader 學習筆記 6 深度寫入的透明度混合

深度寫入開啟 ZWrite on
深度寫入關閉 ZWrite off

  • 原始碼:


Shader "_MyShader/5_Alpha/2_AlphaBlend_ZWrite"

{

    Properties

    {

        _Color ("Color ", COLOR) = (1,1,1,1)

            _MainTex ("Texture", 2D) = "white" {}

            _AlphaScale ("AlphaScale", Range(0,1)) = 1

    }

    SubShader

    {

        Tags {"Queue" = "Transparent" "IgnoreProjecter" = "true" "RenderType" = "Transparent"}



        pass {

            ZWrite on

            ColorMask 0

        }



        pass {

            Tags {"LightMode" = "ForwardBase"}

            ZWrite off

            Blend SrcAlpha OneMinusSrcAlpha



            CGPROGRAM



            #pragma vertex vert

            #pragma fragment frag



            #include "Lighting.cginc"

            #include "UnityCG.cginc"



            fixed4 _Color;

            sampler2D _MainTex;

            float4 _MainTex_ST;

            fixed _AlphaScale;



            struct a2v {

                float4 vertex: POSITION;

                float3 normal: NORMAL;

                float4 texcoord: TEXCOORD0;

            };



            struct v2f {

                float4 pos: SV_POSITION;

                float3 worldNormalDir: POSITION1;

                float3 worldLightDir: POSITION2;

                float2 uv: TEXCOORD0;

            };



            v2f vert(a2v v){

                v2f o;

                o.pos = mul(UNITY_MATRIX_MVP,v.vertex);



                o.worldNormalDir = UnityObjectToWorldNormal(v.normal);

                o.worldLightDir = UnityWorldSpaceLightDir(v.vertex);



                o.uv = TRANSFORM_TEX(v.texcoord,_MainTex);



                return o;

            }



            fixed4 frag(v2f i):SV_Target{

                fixed3 normalDir = normalize(i.worldNormalDir);

                fixed3 lightDir = normalize(i.worldLightDir);

                fixed4 tex = tex2D(_MainTex,i.uv);



                //AlphaTest

                //if(tex.a - _CutOff <= 0)

                //    discard;

                //clip(tex.a - _CutOff);



                fixed3 albedo = tex.rgb *_Color.rgb;



                fixed3 ambient = UNITY_LIGHTMODEL_AMBIENT.xyz * albedo;



                fixed3 diffuseC = _LightColor0.rgb * albedo * saturate(dot(normalDir,lightDir));



                fixed4 col = fixed4(ambient + diffuseC,tex.a * _AlphaScale);

                return col;

            }



            ENDCG

        }



    }



    FallBack "diffuse"

}




效果圖:

在這裡插入圖片描述

可以看到遠一點的透明小球可以被近的小球遮擋,這是因為開啟了深度寫入。