Unity3D Shader 之 _Time 時間

_Time 用來驅動shader內部的動畫。我們可以用它來計算時間的變換。基於此可以在shader中實現各種動畫效果。

官方提供了下面幾個變量供我們使用

//t是自該場景加載開始所經過的時間,4個分量分別是 (t/20, t, t*2, t*3) _Time float4 time (t/20, t, t*2, t*3), //t 是時間的正弦值,4個分量分別是 (t/8, t/4, t/2, t) _SinTime float4 Sine of time: (t/8, t/4, t/2, t). //t 是時間的餘弦值,4個分量分別是 (t/8, t/4, t/2, t) _CosTime float4 Cosine of time: (t/8, t/4, t/2, t). //dt 是時間增量,4個分量的值分別是(dt, 1/dt, smoothDt, 1/smoothDt) nity_DeltaTime float4 Delta time: (dt, 1/dt, smoothDt, 1/smoothDt).

如果使用 fixed x= Speed * _Time; 等價於 fixed x= Speed * _Time.x;

_Time各個分量的值如下:

_Time.x = time / 20

_Time.y = time

_Time.z = time * 2

_Time.w = time * 3

那麼_SinTime.w 等價於 sin(_Time.y)

下面的代碼實現了Plane的定點 y值 依賴於 x的座標隨時間變化,這樣可以實現類似波浪的效果

// Upgrade NOTE: replaced '_Object2World' with 'unity_ObjectToWorld' Shader "Unlit/TestTime" { Properties { _MainTex ("Texture", 2D) = "white" {} } SubShader { Tags { "RenderType"="Opaque" } LOD 100 Pass { CGPROGRAM #pragma vertex vert #pragma fragment frag // make fog work // #pragma multi_compile_fog #include "UnityCG.cginc" struct appdata { float4 vertex : POSITION; float2 uv : TEXCOORD0; }; struct v2f { float2 uv : TEXCOORD0; float4 vertex : POSITION; }; sampler2D _MainTex; float4 _MainTex_ST; v2f vert (appdata v) { v2f o; v.vertex.y = sin(v.vertex.x+_Time.y); o.vertex = UnityObjectToClipPos(v.vertex); o.uv = v.uv; return o; } fixed4 frag (v2f i) : SV_Target { fixed4 col = tex2D(_MainTex, i.uv); return col; } ENDCG } } }

效果如下