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
 }
 }
}

效果如下

Unity3D Shader 之 _Time 时间


分享到:


相關文章: