上代码:
Shader "Shader入门/透明度效果/AlphaBlendShader"
{Properties{_MainTex ("Texture", 2D) = "white" {}_AlphaScale("AlphaScale",Range(0,1))=1.0}SubShader{Tags { "RenderType"="Transparent" "IgnoreProjector"="True" "RenderType"="Transparent" }Pass{ZWrite On ColorMask 0}Pass{Tags{"LightMode"="ForwardBase"}ZWrite Off Blend SrcAlpha OneMinusSrcAlphaCGPROGRAM#pragma vertex vert#pragma fragment frag#include "UnityCG.cginc"#include "Lighting.cginc"struct appdata{float4 vertex : POSITION;float2 texcoord : TEXCOORD0;float3 normal : NORMAL;};struct v2f{float4 pos : SV_POSITION;float2 uv : TEXCOORD0;float3 normal_world : TEXCOORD1;float3 pos_world : TEXCOORD2;};sampler2D _MainTex;float4 _MainTex_ST;float _AlphaScale;v2f vert (appdata v){v2f o;o.pos = UnityObjectToClipPos(v.vertex);o.uv = TRANSFORM_TEX(v.texcoord, _MainTex);o.normal_world = mul(v.normal,unity_WorldToObject);o.pos_world = mul(unity_ObjectToWorld,v.vertex);return o;}fixed4 frag (v2f i) : SV_Target{half3 worldNormal = normalize(i.normal_world);half3 worldLightDir = UnityWorldSpaceLightDir(i.pos_world);// sample the texturefixed4 col = tex2D(_MainTex, i.uv);fixed3 abledo = col.rgb;fixed3 ambient = UNITY_LIGHTMODEL_AMBIENT.xyz*abledo;fixed3 diffuse = _LightColor0.rgb*abledo*max(0,dot(worldNormal,worldLightDir));fixed3 final_color = ambient+diffuse;return fixed4(final_color,col.a*_AlphaScale);}ENDCG}}
}
效果:
在代码中我们有两个Pass,首先在第二个Pass中我们实现了AlphaBlend的基础实现,关闭了深度写入和进行了混合,对于上述的混合模式,实际为:
Blend SrcFactor DstFactor(开启混合,并设置混合因子。源颜色【该片元产生的颜色】会乘以SrcFactor,而目标颜色【已经存在于颜色缓存中的颜色】会乘以DstFactor,最后两者相加)
及:
而对于第一个Pass是开启了深度写入和颜色遮罩进行不输出颜色操作,这样可以解决复杂模型间存在深度的问题效果
ColorMask RGB|A|0|任何其它的R、G、B
当设置为0时意味着该Pass不写入任何颜色通道,即不会输出任何颜色。