Unity Shader系列文章:Unity Shader目錄-初級篇
Unity Shader系列文章:Unity Shader目錄-中級篇
效果如下:

溶解效果.jpg

材質(zhì).png

噪聲貼圖.png
// 溶解效果(帶泛光)
// 實(shí)現(xiàn)思路:采樣無序圖,然后通過其中的某個(gè)通道(此處為r)的值,與當(dāng)前的溶解系數(shù)對比,
// 如果主紋理當(dāng)前的通道值小于溶解系數(shù),則說明當(dāng)前片元需要被剔除。
// 如果不被剔除,則判斷當(dāng)前值距離消融的比例來設(shè)置消融的邊緣顏色混合
Shader "Custom/DissolveOneColor"
{
Properties
{
_MainTexture ("Main Texture(RGB)", 2D) = "white" { }
_DissolveTexture ("Dissolve Texture(R)", 2D) = "white" { }// 噪聲圖
_EdgeColor ("EdgeColor", Color) = (1, 1, 1, 1) // 邊緣顏色
_DissolveAmount ("DissolveAmount", Range(0, 1)) = 1 // 溶解系數(shù)
_EdgeWidth ("EdgeWidth", Range(0, 0.3)) = 0.05 // 邊緣寬度
}
SubShader
{
Tags { "RenderType" = "Opaque" }
LOD 100
Cull off
Pass
{
CGPROGRAM
#pragma vertex vert // 聲明頂點(diǎn)著色程序函數(shù)名
#pragma fragment frag // 聲明片元著色程序函數(shù)
#include "UnityCG.cginc"
sampler2D _MainTexture;
sampler2D _DissolveTexture;
float _DissolveAmount;
float _ExtrudeAmount;
float _EdgeWidth;
fixed4 _EdgeColor;
// 應(yīng)用傳給頂點(diǎn)著色程序的數(shù)據(jù)
struct appdata
{
float4 vertex: POSITION; // 模型的頂點(diǎn)坐標(biāo)
float2 uv: TEXCOORD; // 模型的紋理坐標(biāo)
};
// 頂點(diǎn)著色程序傳遞給片元程序的數(shù)據(jù)
struct v2f
{
float4 pos: SV_POSITION; // 裁剪空間中的頂點(diǎn)坐標(biāo)
float2 uv: TEXCOORD; // 模型的紋理坐標(biāo)
};
v2f vert(appdata v)
{
v2f o;
o.pos = UnityObjectToClipPos(v.vertex); // 模型空間頂點(diǎn)坐標(biāo)轉(zhuǎn)換為裁剪空間下坐標(biāo)
o.uv = v.uv; // 紋理uv坐標(biāo)
return o;
}
fixed4 frag(v2f i): SV_TARGET
{
fixed4 dissolveColor = tex2D(_DissolveTexture, i.uv);
// 溶解貼圖上的R通道值和目前的溶解基準(zhǔn)值相差多少
float offsetValue = dissolveColor.r - _DissolveAmount;
// offsetValue < 0 則放棄此片元不繪制
clip(offsetValue);
fixed4 textureColor = tex2D(_MainTexture, i.uv);
offsetValue += (1 - sign(_DissolveAmount)) * _EdgeWidth;
float edgeFactor = 1 - saturate(offsetValue / _EdgeWidth);
return lerp(textureColor, _EdgeColor, edgeFactor);
}
ENDCG
}
}
}