1.代码
Shader "Custom/Twist"
{
Properties
{
_MainTex ("Texture", 2D) = "white" {}
//扭曲
_Bend("Bend", Range(-1, 1)) = 0.354
//偏移_X
_PosX("PosX", Range(-1, 2)) = 0.5
//偏移_Y
_PosY("PosY", Range(-1, 2)) = 0.5
//旋转半径
_Radius("Radius", Range(0, 1)) = 0.5
//速度
_Speed("Speed", Range(-10, 10)) = 2.679
//插值
_LerpUV_Fade("LerpUV_Fade", Range(0, 1)) = 1
//褪色
_SpriteFade("SpriteFade", Range(0, 1)) = 1.0
}
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;
float4 color : COLOR;
};
struct v2f
{
float2 uv : TEXCOORD0;
float4 vertex : SV_POSITION;
float4 color : COLOR;
};
sampler2D _MainTex;
float _Bend;
float _PosX;
float _PosY;
float _Radius;
float _Speed;
float _LerpUV_Fade;
float _SpriteFade;
//UV扭曲动画
//value : 扭曲
//posx : 偏移量X
//posy : 偏移量Y
//radius : 旋转半径
//speed : 旋转速度
float2 AnimatedTwistUV(float2 uv, float value, float posx, float posy, float radius, float speed)
{
//中心点
float2 center = float2(posx, posy);
//获取UV顶点到中心的向量
float2 tc = uv - center;
//根据向量获取长度
float dist = length(tc);
//如果长度小于旋转半径,范围内旋转
if (dist < radius)
{
//百分比 越靠近中心点,扭曲度越大
float percent = (radius - dist) / radius;
//中心推移量
float theta = percent * percent * 16.0 * sin(value);
//正弦、余弦,用中心推移量乘以时间乘以速度,得到旋转动画
float s = sin(theta + _Time.y * speed);
float c = cos(theta + _Time.y * speed);
tc = float2(dot(tc, float2(c, -s)), dot(tc, float2(s, c)));
}
//归位
tc += center;
return tc;
}
v2f vert (appdata v)
{
v2f o;
o.vertex = UnityObjectToClipPos(v.vertex);
o.uv = v.uv;
o.color = v.color;
return o;
}
fixed4 frag (v2f i) : SV_Target
{
//UV扭曲动画
float2 tuv = AnimatedTwistUV(i.uv,_Bend,_PosX,_PosY,_Radius,_Speed);
//插值,,可以控制UV在处理后与处理前标量
i.uv = lerp(i.uv,tuv,_LerpUV_Fade);
//纹理采样
float4 mcolor = tex2D(_MainTex,i.uv);
//声明最终结果
float4 res = mcolor;
res.rgb *= i.color.rgb;
//褪色处理
res.a = res.a * _SpriteFade * i.color.a;
return res;
}
ENDCG
}
}
}
2.效果: