上代码:
Shader "Shader入门/透明度效果/AlphaTestShader"
{
Properties
{
_MainTex ("Texture", 2D) = "white" {}
_CutOff("CutOff",Range(0,1))=1
}
SubShader
{
Tags { "Queue"="AlphaTest" "IgnoreProjector"="True" "RenderType"="TransparentCutout" }
Pass
{
Tags{"LightMode"="ForwardBase"}
CGPROGRAM
#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 _CutOff;
v2f vert (appdata v)
{
v2f o;
o.pos = UnityObjectToClipPos(v.vertex);
o.uv = TRANSFORM_TEX(v.texcoord, _MainTex);
o.normal_world = UnityObjectToWorldNormal(v.normal);
o.pos_world = mul(unity_ObjectToWorld,v.vertex);
return o;
}
fixed4 frag (v2f i) : SV_Target
{
half3 worldNormal = normalize(i.normal_world);
half3 worldLightDir = normalize(UnityWorldSpaceLightDir(i.pos_world));
// sample the texture
fixed4 col = tex2D(_MainTex, i.uv);
clip(col.a-_CutOff);
fixed3 albedo = col.rgb;
fixed3 ambient = UNITY_LIGHTMODEL_AMBIENT.xyz*albedo;
fixed3 diffuse = _LightColor0.rgb*albedo*max(0,dot(worldLightDir,worldNormal));
fixed3 final_color = diffuse+ambient;
return fixed4(final_color,1.0);
return col;
}
ENDCG
}
}
}
其中核心的一块是clip(float x)函数,当x的值小于0时这块偏远会被舍弃,根据一个阈值参数我们进行调控AlphaTest的阈值。(贴图需要有透明度通道)
效果:
从效果我们也可以看到,AlphaTest的透明效果很极端,要么完全不透明,要么完全透明