DAY 13
0

## 目標

• `_Time`: 場景載入開始經過的時間
• `_SinTime`: 時間的正弦值
• `_CosTime`: 時間的餘弦值
• `_unity_DeltaTime`: 時間之間的差量

## 無限捲動背景

### 開始撰寫!

``````Shader "Learning/InfinityScrollBg"
{
Properties
{
_BackTex ("Back Layer", 2D) = "white" {}
_FrontTex ("Front Layer", 2D) = "white" {}
_BackScrollSpeed ("Back Layer Scroll Speed", Float) = 1.0
_FrontScrollSpeed ("Front Layer Scroll Speed", Float) = 1.0
}
{
Tags { "RenderType"="Opaque" "Queue"="Geometry" }

Pass
{
Tags { "LightMode"="ForwardBase" }

CGPROGRAM
#pragma vertex vert
#pragma fragment frag

#include "UnityCG.cginc"

struct appdata
{
float4 vertex : POSITION;
float4 uv : TEXCOORD0;
};

struct v2f
{
float4 vertex : SV_POSITION;
// 把後景跟前景的紋理座標放在同一組座標變數中
// 為了減少快取的使用
float4 uv : TEXCOORD0;
};

sampler2D _BackTex;
float4 _BackTex_ST;
sampler2D _FrontTex;
float4 _FrontTex_ST;
float _BackScrollSpeed;
float _FrontScrollSpeed;

v2f vert (appdata v)
{
v2f o;
o.vertex = UnityObjectToClipPos(v.vertex);
// 後面的 "frac(float2(_Speed, 0.0) * _Time.y)" 視為每秒位移的變化量
o.uv.xy = TRANSFORM_TEX(v.uv, _BackTex) + frac(float2(_BackScrollSpeed, 0.0) * _Time.y);
o.uv.zw = TRANSFORM_TEX(v.uv, _FrontTex) + frac(float2(_FrontScrollSpeed, 0.0) * _Time.y);
return o;
}

fixed4 frag (v2f i) : SV_Target
{
fixed4 firstLayer = tex2D(_BackTex, i.uv.xy);
fixed4 secondLayer = tex2D(_FrontTex, i.uv.zw);

// 利用lerp將2nd Layer跟1st Layer混合再一起
fixed4 c = lerp(firstLayer, secondLayer, secondLayer.a);

return c;
}
ENDCG
}
}
}
``````

## 圖像序列動畫(Image Sequence Animation)

from Open Game Art

``````Shader "Learning/ISA"
{
Properties
{
_Color ("Color Tint", Color) = (1, 1, 1, 1)
_MainTex ("Image Sequence", 2D) = "white"{}
// 水平與垂直的數目，若拿範例圖這裡的數目是8x8
_HorizontalAmount ("Horizontal Amount", Float) = 4
_VerticalAmount ("Vertical Amount", Float) = 4
_Speed ("Animation Speed", Range(0, 100)) = 30
}
{
Tags { "Queue"="Transparent" "IgnoreProjector"="True" "RenderType"="Transparent" }

Pass
{
Tags { "LightMode"="ForwardBase" }

ZWrite Off
Blend SrcAlpha OneMinusSrcAlpha

CGPROGRAM
#pragma vertex vert
#pragma fragment frag

#include "UnityCG.cginc"

struct appdata
{
float4 vertex : POSITION;
float2 uv : TEXCOORD0;
};

struct v2f
{
float2 uv : TEXCOORD0;
float4 vertex : SV_POSITION;
};

fixed4 _Color;
sampler2D _MainTex;
float4 _MainTex_ST;
float _HorizontalAmount;
float _VerticalAmount;
float _Speed;

v2f vert (appdata v)
{
v2f o;
o.vertex = UnityObjectToClipPos(v.vertex);
o.uv = TRANSFORM_TEX(v.uv, _MainTex);
return o;
}

fixed4 frag (v2f i) : SV_Target
{
float time = floor(_Time.y * _Speed);
float row = floor(time / _HorizontalAmount);    // x index
float column = time - row * _HorizontalAmount;  // y index

// 負號是因為原圖是從左上到右下，texture coordinate是從左下到右上
half2 uv = i.uv + half2(column, -row); // 根據時間更新座標

uv.x /= _HorizontalAmount;
uv.y /= _VerticalAmount;

fixed4 c = tex2D(_MainTex, uv);
c.rgb *= _Color;
return c;
}
ENDCG
}
}
}

``````