Shader 听起来高深,本质就是把「屏幕上每个像素该是什么颜色」用代码描述出来。本文用一个流动光带效果入门。
目标效果
让模型表面出现一道沿 UV 方向循环流动的高亮光带,常用于宝箱、技能特效。
完整 Shader
Shader "Custom/FlowBand" {
Properties {
_MainTex ("Main Tex", 2D) = "white" {}
_BandColor ("Band Color", Color) = (1,1,1,1)
_Speed ("Speed", Range(0, 5)) = 1.0
_Width ("Width", Range(0.01, 0.5)) = 0.1
}
SubShader {
Tags { "RenderType"="Opaque" }
CGPROGRAM
#pragma surface surf Lambert
struct Input { float2 uv_MainTex; };
sampler2D _MainTex;
fixed4 _BandColor;
float _Speed, _Width;
void surf (Input IN, inout SurfaceOutput o) {
fixed4 c = tex2D(_MainTex, IN.uv_MainTex);
float pos = frac(IN.uv_MainTex.x + _Time.y * _Speed);
float band = smoothstep(1.0 - _Width, 1.0, pos)
- smoothstep(1.0, 1.0, pos);
o.Albedo = c.rgb + _BandColor.rgb * band;
}
ENDCG
}
}关键点
_Time.y 是 Unity 内置的时间变量;frac 让 UV 取小数部分实现循环;两个 smoothstep 相减得到一条宽度可控的光带。
调参建议
- 想要光带更柔和:增大
_Width或使用pow(band, 0.5)。 - 想要彩虹色:把
_BandColor换成基于pos的 HSV 采样。 - 想要跟随角色移动方向:把世界空间坐标投影到 UV。
数学基础
光带强度沿 UV.x 的高斯分布近似:
下一篇我们会把这个效果升级为屏幕后处理描边,敬请期待。