11.2.2滚动的背景动画 URP
Shader "Custom/chap11.2.2/Time Animation"
{
Properties
{
_MainTexFar ("Texture", 2D) = "white" {} // 远景
_MainTexNear ("Texture", 2D) = "white" {} // 近景
_Speed1("animation Speed1", Range(0,100)) = 100 // 动画速度
_Speed2("animation Speed2", Range(0,100)) = 50 // 动画速度
_Color1("Main Color", Color) = (1,1,1,1) // 颜色 1
_Color2("Main Color", Color) = (1,1,1,1) // 颜色 2
}
SubShader
{
// 序列帧动画通常带有透明度, 因此这里的 renderType 和 Queue 均设置为 Transparent
Tags { "RenderPipeLine"="UniversalRenderPipeline" "RenderType"="Transparent" "Queue"="Transparent" "IgnoreProjector"="true" }
// 透明模式下通常关闭深度写入
ZWrite Off
// 指定混合因子
Blend SrcAlpha OneMinusSrcAlpha
HLSLINCLUDE
#include "Packages/com.unity.render-pipelines.universal/ShaderLibrary/Core.hlsl"
#include "Packages/com.unity.render-pipelines.universal/ShaderLibrary/Lighting.hlsl"
#include "Packages/com.unity.render-pipelines.core/ShaderLibrary/SpaceTransforms.hlsl"
CBUFFER_START(UnityPerMaterial)
float4 _MainTexFar_ST;
float4 _MainTexNear_ST;
half4 _Color1;
half4 _Color2;
float _Speed1;
float _Speed2;
CBUFFER_END
ENDHLSL
Pass
{
Tags { "LightMode"="UniversalForward" }
HLSLPROGRAM
#pragma vertex vert
#pragma fragment frag
TEXTURE2D (_MainTexFar);
SAMPLER(sampler_MainTexFar);
TEXTURE2D (_MainTexNear);
SAMPLER(sampler_MainTexNear);
struct appdata
{
float4 vertex : POSITION;
float2 uv : TEXCOORD0;
float3 normal: NORMAL;
};
struct v2f
{
float4 uv : TEXCOORD0;
// UNITY_FOG_COORDS(1)
float4 vertex : SV_POSITION;
float3 worldNormal: TEXCOORD1;
float3 worldPos: TEXCOORD2;
};
v2f vert (appdata v)
{
v2f o;
// 裁剪空间坐标
o.vertex = TransformObjectToHClip(v.vertex);
// 世界空间法线
o.worldNormal = TransformObjectToWorldNormal(v.normal);
// 世界坐标
o.worldPos = TransformObjectToWorld(o.vertex).xyz;
// uv
o.uv.xy = TRANSFORM_TEX(v.uv, _MainTexNear) + frac(float2(_Time.y * _Speed1, 0));
o.uv.zw = TRANSFORM_TEX(v.uv, _MainTexFar)+frac(float2(_Time.y * _Speed2, 0));
return o;
}
float4 frag (v2f i) : SV_Target
{
// _time.y = t;
float time1 = floor(_Time.y * _Speed1);
float time2 = floor(_Time.y * _Speed2);
float3 worldNormal = normalize(i.worldNormal);
Light light = GetMainLight();
// i.uv.xy += frac(float2(_Time.y * _Speed1, 0));
// i.uv.zw += frac(float2(_Time.y * _Speed2, 0));
float4 texColor1 = SAMPLE_TEXTURE2D(_MainTexNear, sampler_MainTexNear ,i.uv.xy);
float4 texColor2 = SAMPLE_TEXTURE2D(_MainTexFar, sampler_MainTexFar ,i.uv.zw);
float4 albedo1 = texColor1 * _Color1;
float4 albedo2 = texColor2 * _Color2;
float4 albedo = lerp(albedo1, albedo2, albedo2.a);
// 环境光
float3 ambient = _GlossyEnvironmentColor.xyz * albedo;
float3 worldLightDir = TransformObjectToWorldDir(light.direction);
// 漫反射光 半兰伯特
float3 diffuse = light.color.rgb * albedo * saturate(dot(worldNormal, worldLightDir) * 0.5 + 0.5);
float3 col = ambient + diffuse;
return float4(col, albedo.a);
}
ENDHLSL
}
}
}
效果图