![](https://img.haomeiwen.com/i13097306/1d32850cd01438bd.jpg)
0.本文示例代码地址
1. 消融预期效果
![](https://img.haomeiwen.com/i13097306/2284c89b224737fb.gif)
2. 核心思路
让模型的部分像素不显示,不显示的部分和依然显示的部分交界处显示“消融颜色”。随时间推移,不显示的部分越来越大直到完全不显示,通过噪声纹理来确定不同像素消融的先后顺序。
- 在片元着色器中对噪声纹理采样,读取某个通道的分量,和阈值 amount 进行大小对比,确定当前片元是否显示
- 随时间变化不断调整阈值 amout 的值,以确保越来越多像素不会显示
- 定义一个变量 width,当片元着色器中针对噪声纹理采样得到的某个分量在 amout 和 width 之间时,显示“消融颜色”
3. 代码
Shader "Custom_Shader/Dissolve"
{
Properties
{
_MainTex ("Texture", 2D) = "white" {}
_NoiseTex ("Noise Tex", 2D) = "white" {}
_LineWidth ("Line Width", Range(0.0, 0.3)) = 0.1
_Speed ("Speed", float) = 1.0
_DissolveColor ("DissolveColor", Color) = (1.0, 1.0, 1.0, 1.0)
}
SubShader
{
Tags { "RenderType"="Opaque" }
LOD 100
Pass
{
Cull Off
CGPROGRAM
#pragma vertex vert
#pragma fragment frag
#include "UnityCG.cginc"
struct appdata
{
float4 vertex : POSITION;
float2 uv : TEXCOORD0;
};
struct v2f
{
float2 uv : TEXCOORD0;
float4 vertex : SV_POSITION;
};
sampler2D _MainTex;
float4 _MainTex_ST;
sampler2D _NoiseTex;
float4 _NoiseTex_ST;
float _LineWidth;
float _Speed;
float4 _DissolveColor;
v2f vert (appdata v)
{
v2f o;
o.vertex = UnityObjectToClipPos(v.vertex);
o.uv = TRANSFORM_TEX(v.uv, _MainTex);
return o;
}
fixed4 frag (v2f i) : SV_Target
{
fixed4 noiseColor = tex2D(_NoiseTex, i.uv);
float amount = frac(_Time.y * _Speed);
// float amount = 0.5;
clip(noiseColor.r - amount);
if (noiseColor.r - amount < _LineWidth) {
return _DissolveColor;
}
fixed4 col = tex2D(_MainTex, i.uv);
return col;
}
ENDCG
}
}
}
4. 关键代码分析
顶点着色器只完成最基本的作用,效果都在片元着色器中实现。
- 针对噪声纹理采样
fixed4 noiseColor = tex2D(_NoiseTex, i.uv);
- 确定像素是否显示,这里使用了噪声纹理的 g 通道做阈值
clip(noiseColor.r - amount);
- 跟随时间变化阈值,且暴露消融速度的控制参数
float amount = frac(_Time.y * _Speed);
- 消融宽度的实现
if (noiseColor.r - amount < _LineWidth)
{
return _DissolveColor;
}
5. 效果优化和扩展:消融颜色渐变
上述实现在消融部分都是纯颜色,希望消融颜色有渐变过程,可以模拟燃烧效果,针对在 _LineWidth 范围内的像素进行处理,增加两个颜色控制变量_DissolveInnerColor
和_DissolveOuterColor
,以及消融颜色过渡代码:
if (noiseColor.r - amount < _LineWidth)
{
float t = smoothstep(0.0, _LineWidth, noiseColor.r - amount);
return lerp(_InnerColor, _OuterColor, t);
}
最终效果对比
![](https://img.haomeiwen.com/i13097306/bdfb76fc3f6cb5bb.gif)
网友评论