此篇文章用Unity 的UnityShader代码分别实现了以下材质溶解效果。
上述效果主要可拆解为两个部分,一是噪声裁剪,二是裁剪边缘上色。
1.边缘裁剪
在UnityShader中,材质的裁剪主要采用Clip(value)函数,value > 0则显示,value < 0则不显示。
由图中我们可以看到主要是裁剪的value主要和noise纹理和模型顶点的高度有关,我们可以自行设计一个裁剪函数:
(height是顶点在模型空间的Y值,Burning Value是可在材质实例中暴露的可控变量,noise是传入的2D纹理)
//获取噪波纹理的红色通道(其他通道g/b亦可)
float noise = tex2D(_NoiseTex,i.uv*_NoiseScale).r;
//加上0.5,防止当_BurningValue=0时,在模型轴心(y=0)的xz轴面上切除一条平整的切线
float burn = _BurningValue * noise + 0.5;
//获取顶点在模型空间的高度
float height = i.localPosition.y;
2.边缘高亮
边缘高亮其实就是在BurningValue*noise的基础上加一个变量BurnWidth,多裁剪出一点点边,然后添加上你想要的颜色BurnColor。
float s1= step(height,burn);
float s2 = step(height,burn + _BurningWidth); //在裁剪边缘增加一点偏移
float colorRange = s2-s1;
return lerp(tex,tex+_BurnColor,colorRange);
完整代码如下:
Shader "Unlit/Shader_BurningFade"
{
Properties
{
_MainTex ("_MainTex", 2D) = "white" {}
_NoiseTex ("_NoiseTex", 2D) = "white" {}
_BurningValue ("_BurningValue",float) = 1
_BurningWidth ("_BurningWidth",float) = 0
_NoiseScale ("_NoiseScale",float) = 1
[HDR]_BurnColor ("_BurnColor",Color) = (1,1,1,0)
}
SubShader
{
Tags { "RenderType"="Opaque" }
LOD 100
Pass
{
CGPROGRAM
#pragma vertex vert
#pragma fragment frag
// make fog work
#pragma multi_compile_fog
#include "UnityCG.cginc"
struct appdata
{
float4 vertex : POSITION;
float2 uv : TEXCOORD0;
};
struct v2f
{
float2 uv : TEXCOORD0;
UNITY_FOG_COORDS(1)
float4 vertex : SV_POSITION;
float4 worldNormal : TEXCOORD1;
float3 worldPosition : TEXCOORD2;
float3 localPosition : TEXCOORD3;
};
sampler2D _MainTex;
sampler2D _NoiseTex;
float4 _MainTex_ST;
float _BurningValue,_NoiseScale;
float _BurningWidth;
float4 _BurnColor;
v2f vert (appdata v)
{
v2f o;
o.vertex = UnityObjectToClipPos(v.vertex);
o.uv = TRANSFORM_TEX(v.uv, _MainTex);
UNITY_TRANSFER_FOG(o,o.vertex);
//get the object's location
o.localPosition = v.vertex.xyz;
o.worldPosition = mul(unity_ObjectToWorld,v.vertex).xyz;
return o;
}
float4 frag (v2f i) : SV_Target
{
// sample the texture
float4 tex = tex2D(_MainTex, i.uv);
//获取噪波纹理的红色通道(其他通道g/b亦可)
float noise = tex2D(_NoiseTex,i.uv*_NoiseScale).r;
//加上0.5,防止当_BurningValue=0时,在模型轴心(y=0)的xz轴面上切除一条平整的切线
float burn = _BurningValue * noise + 0.5;
float height = i.localPosition.y; //获取顶点在模型空间的高度
clip(height-burn);
float s1= step(height,burn);
float s2 = step(height,burn + _BurningWidth); //在裁剪边缘增加一点偏移
float colorRange = s2-s1;
return lerp(tex,tex+_BurnColor,colorRange);
// apply fog
//UNITY_APPLY_FOG(i.fogCoord, col);
//return tex;
}
ENDCG
}
}
}