轉自:https://sorumi.xyz/posts/unity-net/
透明測試
因爲使用了 Standard 光照模型,所以有 Glossiness ,Metallic 這些額外參數。
Shader "Custom/AlphaTest"
{
Properties
{
_Color ("Color", Color) = (1, 1, 1, 1)
_MainTex ("Main Texture", 2D) = "white" { }
_AlphaTex ("Alpha Texture", 2D) = "white" { }
_Cutoff ("Alpha Culloff", Range(0, 1)) = 0.5
_BumpMap ("Normal Map", 2D) = "bump" { }
_BumpScale ("Bump Scale", Float) = 1.0
_Glossiness ("Smoothness", Range(0, 1)) = 0.5
_Metallic ("Metallic", Range(0, 1)) = 0.0
}
SubShader
{
Tags { "Queue" = "AlphaTest" "IgnoreProjector" = "True" "RenderType" = "TransparentCutOut" }
LOD 200
CGPROGRAM
#pragma surface surf Standard addshadow fullforwardshadows alphatest:_Cutoff
#pragma target 3.0
sampler2D _MainTex;
sampler2D _AlphaTex;
sampler2D _BumpMap;
struct Input
{
float2 uv_MainTex;
float2 uv_AlphaTex;
};
fixed4 _Color;
float _BumpScale;
float _Glossiness;
float _Metallic;
void surf(Input IN, inout SurfaceOutputStandard o)
{
fixed4 texColor = tex2D(_MainTex, IN.uv_MainTex);
o.Albedo = texColor.rgb * _Color.rgb;
o.Normal = UnpackNormal(tex2D(_BumpMap, IN.uv_AlphaTex)) * _BumpScale;
o.Metallic = _Metallic;
o.Smoothness = _Glossiness;
o.Alpha = tex2D(_AlphaTex, IN.uv_AlphaTex).r;
}
ENDCG
}
FallBack "Transparent/Cutout/VertexLit"
}
設置渲染通道 "Queue" = "AlphaTest"
和渲染類型 "RenderType" = "TransparentCutOut"
編譯指令需要增加 alphatest:_Cutoff
表示使用 Cutoff 作爲判斷透明的閾值,加上 addshadow
來生成正確的陰影投射。
surf 函數中對透明紋理進行採樣 o.Alpha = tex2D(_AlphaTex, IN.uv_AlphaTex).r;
。
最後使用 "Transparent/Cutout/VertexLit"
作爲 Fallback 。
如果 MainTex 和 AlphaTex 是相對應的,可以合併成一張紋理,減少內存佔用。
效果:
只渲染了正面,背面不可見,原因是默認着色器使用背面剔除,只需要取消剔除即可。Cull
有三個值可以選擇: Back
背面剔除, Front
正面剔除, Off
取消剔除。
SubShader
{
Tags { "Queue" = "AlphaTest" "IgnoreProjector" = "True" "RenderType" = "TransparentCutOut" }
LOD 200
Cull Off
CGPROGRAM
...
}
同時在 Inspector 中需要將 Cast Shadow 選項設爲 Two Sided 。
效果:
透明混合
只需要修改幾處代碼:
修改渲染通道和渲染類型
{"Queue"="Transparent" "IgnoreProjector"="True" "RenderType"="Transparent"}
編譯指令修改爲
#pragma surface surf Standard addshadow fullforwardshadows alpha:blend
此時 ZWrite 深度寫入修改無效,默認是 Off 。
或是
#pragma surface surf Standard addshadow fullforwardshadows keepalpha
此時需要制定混合模式 Blend SrcAlpha OneMinusSrcAlpha
並且關閉深度寫入 ZWrite Off
。
傳統的半透明混合總是會在物體交叉、渲染重疊的情況下,出現錯誤的混合效果。如果開啓深度寫入,會令到渲染錯誤很明顯,而關掉的話影響較小一點。
最後 FallBack 制定 "Transparent/VertexLit"會投射陰影