UnityShader3实现转圈与冷却效果
本文实例为大家分享了UnityShader3实现转圈与冷却效果的具体代码,供大家参考,具体内容如下
参考链接:OpenGL Shader实例分析(3)等待标识效果
一、转圈效果
效果图:
如何实现一个圆绕中心点运动呢?原理很简单,就是随着时间的流逝,起始边固定,而另一条边不断地移动,弧度从0到2*PI,只需求出移动边与圆边的交点,然后画圆即可。至于这个交点,因为圆心的uv为(0.5,0.5),所以交点的坐标就是(0.5 - r * cos(a) , 0.5 + r * sin(a))。
Shader "Custom/Loading"
{
Properties
{
_Color ("Color", Color) = (0, 1, 0, 1)
_Speed ("Speed", Range(1, 10)) = 1
_Radius ("Radius", Range(0, 0.5)) = 0.3
}
SubShader
{
Tags { "Queue" = "Transparent" }
Blend SrcAlpha OneMinusSrcAlpha
ZWrite Off
Pass
{
CGPROGRAM
#pragma vertex vert
#pragma fragment frag
#include "UnityCG.cginc"
#define PI 3.14159
struct appdata
{
float4 vertex : POSITION;
float2 uv : TEXCOORD0;
};
struct v2f
{
float4 vertex : SV_POSITION;
float2 uv : TEXCOORD0;
};
fixed4 _Color;
half _Speed;
fixed _Radius;
fixed4 circle(float2 uv, float2 center, float radius)
{
//if(pow(uv.x - center.x, 2) + pow(uv.y - center.y, 2) < pow(radius, 2)) return _Color;
if(length(uv - center) < radius) return _Color;
else return fixed4(0, 0, 0, 0);
}
v2f vert (appdata v)
{
v2f o;
o.vertex = mul(UNITY_MATRIX_MVP, v.vertex);
o.uv = v.uv;
return o;
}
fixed4 frag (v2f i) : SV_Target
{
fixed4 finalCol = (0, 0, 0, 0);
for(int count = 7; count > 1; count--)
{
half radian = fmod(_Time.y * _Speed + count * 0.5, 2 * PI);//弧度
half2 center = half2(0.5 - _Radius * cos(radian), 0.5 + _Radius * sin(radian));
finalCol += circle(i.uv, center, count * 0.01);
}
return finalCol;
}
ENDCG
}
}
}
二.冷却效果
效果图:
参考上面那张原理图,稍加修改就可以了。
Shader "Custom/Cooling"
{
Properties
{
_MainTex ("Texture", 2D) = "white" {}
_Speed ("Speed", Range(1, 10)) = 1
_Color ("Color", Color) = (0, 0, 0, 1)
}
SubShader
{
Pass
{
CGPROGRAM
#pragma vertex vert
#pragma fragment frag
#include "UnityCG.cginc"
#define PI 3.142
struct appdata
{
float4 vertex : POSITION;
float2 uv : TEXCOORD0;
};
struct v2f
{
float4 vertex : SV_POSITION;
float2 uv : TEXCOORD0;
};
sampler2D _MainTex;
float4 _MainTex_ST;
half _Speed;
fixed4 _Color;
v2f vert (appdata v)
{
v2f o;
o.vertex = mul(UNITY_MATRIX_MVP, v.vertex);
o.uv = TRANSFORM_TEX(v.uv, _MainTex);
return o;
}
fixed4 frag (v2f i) : SV_Target
{
fixed4 col = tex2D(_MainTex, i.uv);
//以正中间为中心,所以将uv范围映射到(-0.5, 0.5)
float2 uv = i.uv - float2(0.5, 0.5);
//atan2(y, x):反正切,y/x的反正切范围在[-π, π]内
//-1用于控制方向
float radian = atan2(uv.y, uv.x) * -1 + PI;
float2 radian2 = fmod(_Time.y * _Speed, 2 * PI);
fixed v = step(radian, radian2);
if(v > 0) return col;
else return col * _Color;
}
ENDCG
}
}
}
以上是 UnityShader3实现转圈与冷却效果 的全部内容, 来源链接: utcz.com/z/312770.html