Unity3D內建Shader私房課(三)Decal貼花
阿新 • • 發佈:2019-02-15
在Unity內建Shader的DefaultResourcesExtra的目錄中,有一個很簡單卻很實用的shader——Decal。這是一個貼花著色器,可以在模型的表面新增一個貼花紋理。
Unity內建Shader下載地址。如圖所示:
(程式設計師的審美也就這樣吧……)我們看看Decal的程式碼:
Shader "Legacy Shaders/Decal" { Properties { _Color ("Main Color", Color) = (1,1,1,1) _MainTex ("Base (RGB)", 2D) = "white" {} _DecalTex ("Decal (RGBA)", 2D) = "black" {} } SubShader { Tags { "RenderType"="Opaque" } LOD 250 CGPROGRAM #pragma surface surf Lambert sampler2D _MainTex; sampler2D _DecalTex; fixed4 _Color; struct Input { float2 uv_MainTex; float2 uv_DecalTex; }; void surf (Input IN, inout SurfaceOutput o) { fixed4 c = tex2D(_MainTex, IN.uv_MainTex); half4 decal = tex2D(_DecalTex, IN.uv_DecalTex); c.rgb = lerp (c.rgb, decal.rgb, decal.a); c *= _Color; o.Albedo = c.rgb; o.Alpha = c.a; } ENDCG } Fallback "Legacy Shaders/Diffuse" }
這是一個表面著色器,程式碼非常簡單。唯一要注意的是:lerp (c.rgb, decal.rgb, decal.a)實際上就等於:decal.a*(decal.rgb-c.rgb)+c.rgb也就等於:decal.a*decal+(1-decal.a)*c.rgbBlend SrcAlpha OneMinusSrcAlpha(因為是Opaque,所以透明度也就無所謂了)