Unity Shader案例02--------流光效果

发布时间 2023-03-28 10:50:13作者: 打工仔-也想飞

使用编辑工具Unity2021

直接上代码

Shader "CLF/SetFlowingLight"
{
	Properties
	{
		_MainTex("Texture", 2D) = "white" {}
		//流动控制
		_Progress("Progress",Range(0, 1)) = 0.2
		//光色
		_ScanColor("Scan Color", Color) = (1, 1, 1, 1)
	}
	SubShader
	{
		Tags { "RenderType" = "Opaque" }
		LOD 100

		Pass
		{
			CGPROGRAM
			#pragma vertex vert
			#pragma fragment frag
			#pragma multi_compile_fog

			#include "UnityCG.cginc"

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

			struct v2f
			{
				float3 uv : TEXCOORD0;
				UNITY_FOG_COORDS(1)
				float4 vertex : SV_POSITION;
			};

			sampler2D _MainTex;
			float4 _MainTex_ST;			

			v2f vert(appdata v)
			{
				v2f o;
				o.vertex = UnityObjectToClipPos(v.vertex);
				//获取除了流光方向的UV坐标
				o.uv.xz = TRANSFORM_TEX(v.uv, _MainTex);
				//设置流光方向
				o.uv.y = v.vertex.y;
				UNITY_TRANSFER_FOG(o,o.vertex);
				return o;
			}

			float _Progress;
			float4 _ScanColor;

			fixed4 frag(v2f i) : SV_Target
			{
				//流光速度
				float halfWidth = 0.25;
				fixed4 col = tex2D(_MainTex, i.uv);
				//判断流光是否在物体范围内
				if (i.uv.z > _Progress - halfWidth && i.uv.z < _Progress + halfWidth)
				{
					//流光范围和控制
					float dis = (halfWidth - abs(i.uv.z - _Progress)) / halfWidth;					
					//上色
					col.rgb = col.rgb + _ScanColor * dis;
				}
				UNITY_APPLY_FOG(i.fogCoord, col);
				return col;
			}
			ENDCG
		}
	}
}