Unity 消融特效教程之 简单消融效果的快速实现
1、打开Unity,新建一个工程,具体如下图
2、在工程中新建一个 Shader 脚本,双击打开 Shader 进行编辑,具体如下图
3、Shader 脚本具体内容如下:Shader"Custom/Dissolve"{ Properties { _MainTex("Texture",2D)="white"{} _NoiseTex("Noise",2D)="white"{} _Threshold("Threshold",Range(0.0,1.0))=0.5 _EdgeLength("EdgeLength",Range(0.0,0.2))=0.1 _EdgeFirstColor("FirstEdgeColor",Color)=(1,1,1,1) _EdgeSecondColor("SecondEdgeColor",Color)=(1,1,1,1) } SubShader { Tags{"Queue"="Geometry""RenderType"="Opaque"}Pass { CullOff//要渲染背面保证效果正确CGPROGRAM #pragmavertexvert #pragmafragmentfrag #include"UnityCG.cginc"structappdata { float4vertex:POSITION; float2uv:TEXCOORD0; };structv2f { float4vertex:SV_POSITION; float2uvMainTex:TEXCOORD0; float2uvNoiseTex:TEXCOORD1; };sampler2D_MainTex; float4_MainTex_ST;sampler2D_NoiseTex; float4_NoiseTex_ST; float_Threshold; float_EdgeLength; fixed4_EdgeFirstColor; fixed4_EdgeSecondColor; v2fvert(appdatav) { v2fo; o.vertex=UnityObjectToClipPos(v.vertex); o.uvMainTex=TRANSFORM_TEX(v.uv,_MainTex);o.uvNoiseTex=TRANSFORM_TEX(v.uv,_NoiseTex); returno; } fixed4frag(v2fi):SV_Target {//镂空 fixedcutout=tex2D(_NoiseTex,i.uvNoiseTex).r; clip(cutout-_Threshold);//边缘颜色 if(cutout-_Threshold<_EdgeLength) { floatdegree=(cutout-_Threshold)/_EdgeLength; returnlerp(_EdgeFirstColor,_EdgeSecondColor,degree); }fixed4col=tex2D(_MainTex,i.uvMainTex); returncol; } ENDCG } }}
4、导入两张贴图,一个作为底图一个作为消融噪点图,并且设置为精灵图格式,具体如下图
5、在工程中,新建一个 Material ,并且设置 Shader 为刚才新建的 Shader,并且添加材质贴图,改变Threshold 就可以看到消融效果,改变EdgeLength 是调整 消融边缘效果,具体如下图
6、在场景中添加一个 Cube,把材质赋给 Cube,具体如下图
7、在工程中,新建一个脚本 Test,来控制改变材质的Threshold 值,来实现脚本控制消融效果,打开脚本进行编辑,具体如下图
8、Test 脚本具体代码和代码说明如下图
9、Test 脚本具体内容如下:usingUnityEngine;publicclassTest:MonoBehaviour{//获得消融材质,设置消融的当前值,以及消融速度 privateMaterialmat; privatefloatcurrtentValue; publicfloatspeed=1.0f;//Usethisforinitialization voidStart(){//获得消融材质 mat=this.GetComponent<Renderer>().material; } //Updateiscalledonceperframe voidUpdate(){ //差值修改材质消融值,_Threshold为Shader中控制消融的参数 currtentValue=Mathf.Lerp(currtentValue,1.0f,Time.deltaTime*speed); if(!Mathf.Approximately(currtentValue,1.0f)){ mat.SetFloat("_Threshold",currtentValue); }}}
10、脚本编译正确,回到Unity界面,把脚本挂载到 Cube 上,具体如下图
11、运行场景,效果如下图
12、到此,《Unity 消融特效教程之 简单消融效果的快速实现》讲解结束,谢谢