加載效果的實現
最終效果:
左側是表面着色器實現,右側是頂點和片元着色器實現。
表面着色器代碼:
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窗口中默認不透明區域爲黑色。
以上注意的點是我在學習過程中碰到的問題,可能會有其他方法解決,以後學習到了,再回來修改。希望能幫助到想要學習着色器的讀者。