Shader学习之能量场效果

Shader学习之能量场效果_第1张图片

从效果上看,该球体是半透明的,边缘部分泛蓝光,球体表面与其他物体相交的部分会高亮,处在球体内部的其他物体形状抖动变化。

首先,边缘部分泛蓝光,根据观察方向绘制,使用UnityWorldSpaceViewDir;

其次,相交部分高亮,计算场景内物体深度和球体深度差值,相交部分的差值为0,设置相机的depthTextureMode即可生成深度图,在shader中使用_CameraDepthTexture访问深度图,LinearEyeDepth,SAMPLE_DEPTH_TEXTURE_PROJ,UNITY_PROJ_COORD这三个方法和宏的用法我也比较模糊,希望有柳暗花明的一天;

最后,形状抖动变化,变化相机的GrabTexure的uv,使用GrabPass获取GrabTexure。

Shader "chenjd/MyForceField"
{
	Properties
	{
		_Color("Color", Color) = (0, 1, 0, 1)
		_Power("Power", Range(0, 4)) = 1
		_NoiseTexture("NoiseTexture", 2D) = "white" {}
		_DistortStrength("DistortStrength", Range(0,1)) = 0.2
		_DistortTimeFactor("DistortTimeFactor", Range(0,1)) = 0.2
	}
	SubShader
	{
		//ZWrite Off
		Cull Off
		Blend SrcAlpha OneMinusSrcAlpha
		Tags {
			"RenderType"="Transparent"
			"Queue"="Transparent"
		}

		GrabPass
		{
			"_GrabTempTex"
		}

		Pass
		{
			CGPROGRAM
			#pragma target 3.0
			#pragma vertex vert
			#pragma fragment frag
			
			#include "UnityCG.cginc"

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

			struct v2f
			{
				float4 vertex : SV_POSITION;
				float3 normal : NORMAL;
				float4 screenPos : TEXCOORD1;
				float3 viewDir : TEXCOORD3;
				float2 uv :TEXCOORD0;
				float4 grabPos : TEXCOORD2;
			};

			fixed4 _Color;
			float _Power;
			sampler2D _CameraDepthTexture;
			sampler2D _NoiseTexture;
			float4 _NoiseTexture_ST;
			sampler2D _GrabTempTex;
			float4 _GrabTempTex_ST;
			float _DistortTimeFactor;
			float _DistortStrength;
			
			v2f vert (appdata v)
			{
				v2f o;

				o.vertex = UnityObjectToClipPos(v.vertex);
				o.uv = TRANSFORM_TEX(v.uv, _NoiseTexture);
				
				o.normal = UnityObjectToWorldNormal(v.normal);
				o.viewDir = normalize(UnityWorldSpaceViewDir(mul(unity_ObjectToWorld, v.vertex)));

				o.screenPos = ComputeScreenPos(o.vertex);
				COMPUTE_EYEDEPTH(o.screenPos.z);

				o.grabPos = ComputeGrabScreenPos(o.vertex);

				return o;
			}
			
			fixed4 frag (v2f i) : SV_Target
			{
				float rim = pow(1 - abs(dot(i.viewDir, i.normal)), _Power);

				float sceneZ = LinearEyeDepth(SAMPLE_DEPTH_TEXTURE_PROJ(_CameraDepthTexture, UNITY_PROJ_COORD(i.screenPos)));
				float delta = sceneZ - i.screenPos.z;
				float intersection = (1 - delta) * 2;

				float4 offset = tex2D(_NoiseTexture, i.uv - _Time.xy) * _DistortTimeFactor;
				i.grabPos.xy -= offset.xy * _DistortStrength;
				
				float4 col = tex2Dproj(_GrabTempTex, i.grabPos);
				col = col + _Color * max(rim, intersection);

				return col;
			}
			ENDCG
		}
	}
}

学习自https://www.cnblogs.com/murongxiaopifu/p/7050233.html。

你可能感兴趣的:(Unity游戏开发)