加载效果的实现
最终效果:
左侧是表面着色器实现,右侧是顶点和片元着色器实现。
表面着色器代码:
Shader "Custom/Loading_SurfaceShader" {
Properties{
_MainTex("Albedo (RGB)", 2D) = "white" {}
_Speed("Speed",float) = 1
}
SubShader{
Tags { "RenderType" = "Opaque" }//"Queue" = "Transparent" }
CGPROGRAM
#pragma surface surf Lambert alpha
sampler2D _MainTex;
half _Speed;
struct Input
{
float2 uv_MainTex;
};
void surf(Input IN, inout SurfaceOutput o)
{
float rot=-_Speed* _Time.z;
fixed c, s;
sincos(radians(rot), s, c);
fixed2x2 matrixRot = fixed2x2(c,-s,s,c);
fixed2 i = mul(IN.uv_MainTex-0.5,matrixRot)+0.5;
fixed4 color= tex2D(_MainTex, i.xy);
o.Albedo = color.rgb;
fixed2 a = (IN.uv_MainTex - 0.5 )* 2;
if (sqrt(a.x*a.x + a.y*a.y) < 1)
o.Alpha = color.a;
else
o.Alpha = 0;
}
ENDCG
}
FallBack "Diffuse"
}
顶点和片元着色器代码:
Shader "Custom/Loading_VFShader" {
Properties{
_MainTex("Albedo (RGB)", 2D) = "white" {}
_Speed("Speed",float) = 1
}
SubShader{
Tags { "RenderType" = "Opaque" "Queue" = "Transparent" }
Pass
{
Blend SrcAlpha OneMinusSrcAlpha
CGPROGRAM
#pragma vertex vert
#pragma fragment frag
sampler2D _MainTex;
half _Speed;
struct appdata
{
float2 uv:TEXCOORD0;
float4 vertex:POSITION;
};
struct v2f
{
float2 uv:TEXCOORD0;
float4 vertex:POSITION;
};
v2f vert(appdata IN)
{
v2f o;
o.vertex = UnityObjectToClipPos(IN.vertex);
o.uv = IN.uv;
return o;
}
fixed4 frag(v2f i) :SV_Target
{
fixed4 o;
float rot = -_Speed * _Time.z;
fixed c, s;
sincos(radians(rot), s, c);
fixed2x2 matrixRot = fixed2x2(c, -s, s, c);
fixed2 uv = mul(i.uv - 0.5, matrixRot) + 0.5;
fixed4 color = tex2D(_MainTex, uv.xy);
o.rgb = color.rgb;
fixed2 a = (i.uv - 0.5) * 2;
if (sqrt(a.x*a.x + a.y*a.y) < 1)
o.a = color.a;
else
o.a = 0;
return o;
}
ENDCG
} }
}
这里需要注意的是:
1.表面着色器实现的效果不能应用于UGUI上。分别把SurfaceShader和VFShader应用于Image组件上,效果如下图:
左侧是表面着色器实现,右侧是顶点和片元着色器实现。
2.必须设置渲染队列,否则渲染会出问题。即在Tags中不添加"Queue" = "Transparent" ;
表面着色器不设置不设置渲染队列,则只能在Scene窗口中可以看到,在Game窗口中是渲染不出来的。
顶点和片选着色器不设置为“Transparent”渲染队列,则在Game窗口中默认不透明区域为黑色。
以上注意的点是我在学习过程中碰到的问题,可能会有其他方法解决,以后学习到了,再回来修改。希望能帮助到想要学习着色器的读者。