溶解效果实现首先需要一张噪点贴图,在网上随便下了一张:
创建Dissolve.shader,添加基础属性:
代码语言:javascript复制Properties
{
_MainTex ("Main Texture", 2D) = "white" {}
//噪点贴图
_DissolveTex("Dissolve Texture", 2D) = "white" {}
//阈值
_DissolveThreshold("Dissolve Threshold", Range(0, 1)) = 0
}
Dissolve Threshold阈值,用于控制溶解的进度,声明在Properties中,即可在Inspector面板进行控制:
在CGPROGRAM和ENDCG中声明顶点函数和片元函数,添加UnityCG.cginc,其中包含了Unity Shader内置的一些函数。
代码语言:javascript复制CGPROGRAM
#pragma vertex vert
#pragma fragment frag
#include "UnityCG.cginc"
ENDCG
声明数据结构a2v,将其作为参数传递给vert顶点函数,v2f将vertex中输出的数据传递到frag片元函数:
代码语言:javascript复制struct a2v
{
float4 vertex : POSITION;
float2 uv : TEXCOORD0;
};
struct v2f
{
float4 position : SV_POSITION;
float2 uv : TEXCOORD0;
};
POSITION语义指顶点位置,TEXCOORD0语义指uv信息,SV_POSITION语义用于标识经过顶点着色器变换之后的顶点位置。
在CG中获取属性:
代码语言:javascript复制sampler2D _MainTex;
sampler2D _DissolveTex;
float _DissolveThreshold;
最终编写顶点函数和片元函数:
代码语言:javascript复制v2f vert(a2v v)
{
v2f o;
o.position = UnityObjectToClipPos(v.vertex);
o.uv = v.uv;
return o;
}
fixed4 frag(v2f i) : SV_TARGET
{
float4 texColor = tex2D(_MainTex, i.uv);
float4 dissolveColor = tex2D(_DissolveTex, i.uv);
clip(dissolveColor.rgb - _DissolveThreshold);
return texColor;
}
片元函数中clip函数用于将参数小于0的像素点丢弃,当溶解阈值从0到1逐渐变大时,像素点逐渐被完全丢弃,最终实现简单的溶解效果,以下为完整代码:
代码语言:javascript复制Shader "Custom/Dissolve"
{
Properties
{
_MainTex ("Main Texture", 2D) = "white" {}
_DissolveTex("Dissolve Texture", 2D) = "white" {}
_DissolveThreshold("Dissolve Threshold", Range(0, 1)) = 0
}
SubShader
{
Pass
{
CGPROGRAM
#pragma vertex vert
#pragma fragment frag
#include "UnityCG.cginc"
struct a2v
{
float4 vertex : POSITION;
float2 uv : TEXCOORD0;
};
struct v2f
{
float4 position : SV_POSITION;
float2 uv : TEXCOORD0;
};
sampler2D _MainTex;
sampler2D _DissolveTex;
float _DissolveThreshold;
v2f vert(a2v v)
{
v2f o;
o.position = UnityObjectToClipPos(v.vertex);
o.uv = v.uv;
return o;
}
fixed4 frag(v2f i) : SV_TARGET
{
float4 texColor = tex2D(_MainTex, i.uv);
float4 dissolveColor = tex2D(_DissolveTex, i.uv);
clip(dissolveColor.rgb - _DissolveThreshold);
return texColor;
}
ENDCG
}
}
}