前言
Unity2021.3.23
一、实现原理
Time控制UV的变化,再采样一张流光贴图.即可实现流光效果。
二、效果及源码展示
1.流光效果
效果描述:
1.边缘光(菲尼尔),
2.从上到下扫描光.
效果图如下:
代码如下:
Shader "Unlit/ScanCode"
{
Properties
{
_MainTex ("Texture", 2D) = "white" {}
_RimMin("RimMin",Range(-1,1)) = 0.0
_RimMax("RimMax",Range(0,2)) = 1.0
_InnerColor("InnerColor",Color) = (0.0, 0.0, 0.0 ,0.0)
_RimColor("Rim Color", Color) = (1,1,1,1)
_RimIntensity("Rim Intensity", Float) = 1.0
_FlowTilling("Flow Tilling",Vector) = (1,1,0,0)
_FlowSpeed("Flow Speed", Vector)= (1,1,0,0)
_FlowTex("Flow Tex", 2D) = "white"{}
_FlowIntensity("Flow Intensity",Float) = 0.5
_InnerAlpha("Inner Alpha",Range(0.0,1.0)) = 0.0
}
SubShader
{
//Tags { "RenderType"="Opaque" }
Tags { "Queue"="Transparent" }
LOD 100
Pass
{
ZWrite off
Blend SrcAlpha One
CGPROGRAM
#pragma vertex vert
#pragma fragment frag
#include "UnityCG.cginc"
struct appdata
{
float4 vertex : POSITION;
float2 texcoord : TEXCOORD0;
float3 normal : NORMAL;
};
struct v2f
{
float2 uv : TEXCOORD0;
float4 vertex : SV_POSITION;
float3 pos_world :TEXCOORD1;
float3 normal_world : TEXCOORD2;
//轴点的世界空间坐标
float3 pivot_world :TEXCOORD3;
};
sampler2D _MainTex;
float4 _MainTex_ST;
float _RimMin;
float _RimMax;
float4 _InnerColor;
float4 _RimColor;
float4 _RimIntensity;
float4 _FlowTilling;
float4 _FlowSpeed;
sampler2D _FlowTex;
float _FlowIntensity;
float _InnerAlpha;
v2f vert (appdata v)
{
v2f o;
o.vertex = UnityObjectToClipPos(v.vertex);
//float4(v.normal,0.0)如果是向量,后面补0.0
float3 normal_world = mul(float4(v.normal,0.0), unity_WorldToObject);
float3 pos_world = mul(unity_ObjectToWorld,v.vertex).xyz;
o.normal_world = normalize(normal_world);
o.pos_world = pos_world;
//三维向量变成一个四维向量,后面补1.0,
o.pivot_world = mul(unity_ObjectToWorld,float4(0.0, 0.0, 0.0, 1.0));
o.uv = v.texcoord;
return o;
}
fixed4 frag (v2f i) : SV_Target
{
//1.边缘光
half3 normal_world = normalize(i.normal_world);
//视线方向的向量,先拿到世界空间上的摄像机的位置,然后归一化。
//精度上,向量用half3就够了。片元阶段要非常注意性能
half3 view_world = normalize(_WorldSpaceCameraPos.xyz -i.pos_world);
//限制在0-1的范围内
half NdotV = saturate(dot(normal_world, view_world));
half fresnel = 1.0 - NdotV;
fresnel = smoothstep(_RimMin,_RimMax, fresnel);
//自发光
half emiss = tex2D(_MainTex, i.uv).r;
emiss = pow(emiss, 5.0);
half final_fresnel = saturate(fresnel + emiss);
//设置颜色
half3 final_rim_color = lerp(_InnerColor.xyz, _RimColor.xyz *_RimIntensity, final_fresnel);
half final_rim_alpha = final_fresnel;
//2.流光
half2 uv_flow = (i.pos_world.xy - i.pivot_world.xy) * _FlowTilling.xy;
uv_flow =uv_flow + _Time.y * _FlowSpeed.xy;
float4 flow_rgba = tex2D(_FlowTex, uv_flow) * _FlowIntensity;
//整合
float3 final_col = final_rim_color + flow_rgba.xyz;
float final_alpha = saturate(final_rim_alpha + flow_rgba.a + _InnerAlpha);
return float4(final_col,final_alpha);
}
ENDCG
}
}
}
(i.pos_world.xy - i.pivot_world.xy)
用于计算UV位置,达到从上到下的扫描效果.