介紹
紋理貼圖移動特效產(chǎn)生巖漿、瀑布效果實現(xiàn)原理是改變動態(tài)改變紋理坐標uv的值,使之移動
修改UV值來實現(xiàn)紋理貼圖的滾動,其實就是讓一個圖片在滾來滾去,來模擬一些水流效果之類的。
這個效果其實在邏輯代碼中也可以寫,就是修改圖片的坐標,不過在邏輯代碼中的話需要兩張圖片來交替出現(xiàn),而在 Shader中,因為 UV 坐標超過 1之后又會重新從 0 開始,所以只要一個Texture 就可以了。
代碼j介紹
_MainTex 主紋理貼圖
_MainTint 主要顏色
_ScrollXSpeed x軸移動速度
_ScrollYSpeed y軸移動速度
主要是在surf函數(shù)里進行操作
fixed xScrollValue = _ScrollXSpeed * _Time;
fixed yScrollValue = _ScrollYSpeed * _Time;
x、y偏移量隨時間增加
void surf (Input IN, inout SurfaceOutput o) {
fixed2 scrolledUV = IN.uv_MainTex;
fixed xScrollValue = _ScrollXSpeed * _Time;
fixed yScrollValue = _ScrollYSpeed * _Time;
scrolledUV += fixed2(xScrollValue, yScrollValue);
half4 c = tex2D (_MainTex, scrolledUV);
o.Albedo = c.rgb * _MainTint;
o.Alpha = c.a;
}
原理:
- _Time是 unity shaderlab內(nèi)置值
- 這里用到了 Unity 提供的一個內(nèi)置變量 _Time_Time 是一個 float4變量,值為 值為 Time (t/20, t, t2, t3), t 就是時間,就是說Unity給我們幾個內(nèi)定的時間速度來使用,默認是取X值。
- 因為 _Time 一直在變化,所以 uv 也一直在變化,所以我們才能得到圖片滾動的效果。
- float4 _Time : Time (t/20, t, t2, t3)
- 是一個四維向量
- scrolledUV += fixed2(xScrollValue, yScrollValue);
- uv的x,y值隨時間累加偏移量
- float4 _Time : Time (t/20, t, t2, t3)
- 最后整合uv與主顏色到當前紋理上,產(chǎn)生了這種移動的效果
運行圖
demo_1_1.gif
完整代碼
Shader "CookBookShaders/Scroll UV" {
Properties {
_MainTex ("Base (RGB)", 2D) = "white" {}
//默認值就是白色
_MainTint ("Diffuse Tint", Color) = (1, 1, 1, 1)
_ScrollXSpeed ("XSpeed", Range (0, 100)) = 2
_ScrollYSpeed ("XSpeed", Range (0, 100)) = 2
}
SubShader {
Tags { "RenderType"="Opaque" }
LOD 200
CGPROGRAM
#pragma surface surf Lambert
sampler2D _MainTex;
float _ScrollXSpeed;
float _ScrollYSpeed;
fixed4 _MainTint;
struct Input {
float2 uv_MainTex;
};
void surf (Input IN, inout SurfaceOutput o)
{
//根據(jù)時間增加,修改 uv_MainTex ,例如從 (0,0) 到 (1,1) ,這樣就類似于貼圖在反方向運動。
fixed2 scrolledUV = IN.uv_MainTex;
fixed xScrollOffset = _ScrollXSpeed * _Time;
//注意_Time這個內(nèi)置變量是float4 值為 Time (t/20, t, t*2, t*3),
//就是說Unity給我們幾個內(nèi)定的時間速度來使用,默認是取X值。
fixed yScrollOffset = _ScrollYSpeed * _Time;
scrolledUV += fixed2(xScrollOffset,yScrollOffset);
half4 c = tex2D (_MainTex, scrolledUV);
o.Albedo = c.rgb * _MainTint;
o.Alpha = c.a;
}
ENDCG
}
FallBack "Diffuse"
}