UnityShader 纹理动画
序列帧动画
Shader "Custom/ImageSequenceAnimationMat"
{
Properties
{
_MainTex ("Texture", 2D) = "white" {}
_HorizontalAmount("Horizontal Amount", float) = 1
_VerticalAmount("Vertical Amount", float) = 1
_Speed("Speed", float) = 1
}
SubShader
{
Tags { "RenderType"="Opaque" "Queue" = "Transparent" "IgnoreProjection" = "True"}
Pass
{
Tags{ "LightMode" = "ForwardBase" }
ZWrite Off
Blend SrcAlpha OneMinusSrcAlpha
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;
float _HorizontalAmount;
float _VerticalAmount;
float _Speed;
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
{
float time = floor(_Time * _Speed * 300.0);
float row = floor(time / _HorizontalAmount);
float column = time - row * _HorizontalAmount;
half2 uv = half2(i.uv.x / _HorizontalAmount, i.uv.y / _VerticalAmount);
uv.x += column / _HorizontalAmount;
uv.y -= row / _VerticalAmount;
fixed4 col = tex2D(_MainTex, uv);
return col;
}
ENDCG
}
}
}
分析:通过时间参数,将采样UV映射到纹理贴图的某个部分。
滚动背景动画
Shader "Custom/ScrollingBackgroundMat"
{
Properties
{
_MainTex1 ("Texture1", 2D) = "white" {}
_MainTex2 ("Texture2", 2D) = "white" {}
_TexSpeed1 ("TexSpeed1", float) = 0.1
_TexSpeed2 ("TexSpeed2", float) = 0.1
}
SubShader
{
Tags { "RenderType"="Opaque" }
LOD 100
Pass
{
CGPROGRAM
#pragma vertex vert
#pragma fragment frag
#include "UnityCG.cginc"
struct appdata
{
float4 vertex : POSITION;
float2 uv : TEXCOORD0;
};
struct v2f
{
float4 uv : TEXCOORD0;
float4 vertex : SV_POSITION;
};
sampler2D _MainTex1;
float4 _MainTex1_ST;
sampler2D _MainTex2;
float4 _MainTex2_ST;
float _TexSpeed1;
float _TexSpeed2;
v2f vert (appdata v)
{
v2f o;
o.vertex = UnityObjectToClipPos(v.vertex);
o.uv.xy = TRANSFORM_TEX(v.uv, _MainTex1) + frac(float2(_TexSpeed1, 0) * _Time.y);
o.uv.zw = TRANSFORM_TEX(v.uv, _MainTex2) + frac(float2(_TexSpeed2, 0) * _Time.y);
return o;
}
fixed4 frag (v2f i) : SV_Target
{
fixed4 col_1 = tex2D(_MainTex1, i.uv.xy);
half4 col_2 = tex2D(_MainTex2, i.uv.zw);
half4 Color = lerp(col_2, col_1, col_1.a);
return Color;
}
ENDCG
}
}
}
分析:前景后景两张纹理贴图,根据前景纹理的Alpha通道决定是否绘制第二张纹理(frac函数:返回输入值的小数部分)。
float frac(float v) { // floor函数返回值会向下取值 // floor实验部分可查看《Shader实验室:floor函数》 return v - floor(v); }