Unity Shader教程之 序列帧动画效果的实现
1、在Unity中新建一个工程,并且在场景中添加一个 Plane,具体如下图


2、导入一个序列图,一般的序列图效果如下图


3、在在工程中新建一个Shader 脚本,命名为UVAnimation,双击打开进行代码编辑,具体如下图

4、UVAnimation 脚本具体代码如下图



5、UVAnimation 脚本具体内容如下:
Shader "Custom/UVAnimation" {
Properties
{
_Color("Base Color", Color) = (1,1,1,1)
_MainTex("Base(RGB)", 2D) = "white" {}
}
SubShader
{
tags{"Queue" = "Transparent" "RenderType" = "Transparent" "IgnoreProjector" = "True"}
Blend SrcAlpha OneMinusSrcAlpha
Pass
{
CGPROGRAM
#pragma vertex vert
#pragma fragment frag
#include "UnityCG.cginc"
float4 _Color;
sampler2D _MainTex;
struct v2f
{
float4 pos:POSITION;
float2 uv:TEXCOORD0;
};
float2 moveUV(float2 vertUV)
{
//因为序列图有12帧所以是12
float textureNum = 12.0;
float timePerFrame = 100;
float index = frac(_Time.x / textureNum * timePerFrame);
float2 uvScale = float2(1 / textureNum, 1);
if (index <= uvScale.x)
return vertUV * uvScale;
else if (index <= 2 * uvScale.x)
return vertUV * uvScale + float2(uvScale.x, 0.0);
else if (index <= 3 * uvScale.x)
return vertUV * uvScale + float2(2 * uvScale.x, 0.0);
else if (index <= 4 * uvScale.x)
return vertUV * uvScale + float2(3 * uvScale.x, 0.0);
else if (index <= 5 * uvScale.x)
return vertUV * uvScale + float2(4 * uvScale.x, 0.0);
else if (index <= 6 * uvScale.x)
return vertUV * uvScale + float2(5 * uvScale.x, 0.0);
else if (index <= 7 * uvScale.x)
return vertUV * uvScale + float2(6 * uvScale.x, 0.0);
else if (index <= 8 * uvScale.x)
return vertUV * uvScale + float2(7 * uvScale.x, 0.0);
else if (index <= 9 * uvScale.x)
return vertUV * uvScale + float2(8 * uvScale.x, 0.0);
else if (index <= 10 * uvScale.x)
return vertUV * uvScale + float2(9 * uvScale.x, 0.0);
else if (index <= 11 * uvScale.x)
return vertUV * uvScale + float2(10 * uvScale.x, 0.0);
else
return vertUV * uvScale + float2(11 * uvScale.x, 0.0);
}
v2f vert(appdata_base v)
{
v2f o;
o.pos = mul(UNITY_MATRIX_MVP, v.vertex);
o.uv = moveUV(v.texcoord.xy);
return o;
}
half4 frag(v2f i):COLOR
{
half4 c = tex2D(_MainTex, i.uv) * _Color;
return c;
}
ENDCG
}
}
}
6、脚本编译正确,回到Unity新建一个材质,把Shader设置为新建的 Shader,图片附上对应的序列帧图片,并把材质赋给 Plane,具体如下图


7、运行场景,就实现序列帧动画效果,具体如下图
