在之前的文章中,我们实现了 深度图 和 抓屏 的使用。我们用这些功能来实现一下能量罩效果。
TEXTURE2D(_CameraDepthTexture);SAMPLER(sampler_CameraDepthTexture);
float2 uv = i.positionCS.xy/ _ScreenParams.xy;
float4 cameraDepthTex = SAMPLE_TEXTURE2D(_CameraDepthTexture,sampler_CameraDepthTexture,uv);
float depthTex = LinearEyeDepth(cameraDepthTex,_ZBufferParams);
float4 depth = depthTex + i.positionVS.z;
float4 highLight = 1 - depth;
highLight *= _HighLightFade;
highLight = pow(highLight,_HighLightFade);
highLight *= _HighLightColor;
Shader "MyShader/URP/P4_3"
{
Properties
{
_HighLightColor("HighLightColor",Color) = (0,0,0,0)
_HighLightFade("HighLight",Float) = 1.0
}
SubShader
{
Tags
{
//告诉引擎,该Shader只用于 URP 渲染管线
"RenderPipeline"="UniversalPipeline"
//渲染类型
"RenderType"="Transparent"
//渲染队列
"Queue"="Transparent"
}
//Blend One One
ZWrite Off
Pass
{
Name "Unlit"
HLSLPROGRAM
#pragma vertex vert
#pragma fragment frag
// Pragmas
#pragma target 2.0
// Includes
#include "Packages/com.unity.render-pipelines.core/ShaderLibrary/Color.hlsl"
#include "Packages/com.unity.render-pipelines.universal/ShaderLibrary/Core.hlsl"
#include "Packages/com.unity.render-pipelines.universal/ShaderLibrary/Input.hlsl"
CBUFFER_START(UnityPerMaterial)
half4 _HighLightColor;
half _HighLightFade;
CBUFFER_END
TEXTURE2D(_CameraDepthTexture);SAMPLER(sampler_CameraDepthTexture);
//struct appdata
//顶点着色器的输入
struct Attributes
{
float3 positionOS : POSITION;
float2 uv : TEXCOORD0;
};
//struct v2f
//片元着色器的输入
struct Varyings
{
float4 positionCS : SV_POSITION;
float2 uv : TEXCOORD0;
float4 screenPos : TEXCOORD1;
float3 positionVS : TEXCOORD2;
};
//v2f vert(Attributes v)
//顶点着色器
Varyings vert(Attributes v)
{
Varyings o = (Varyings)0;
float3 positionWS = TransformObjectToWorld(v.positionOS);
o.positionVS = TransformWorldToView(positionWS);
o.positionCS = TransformWViewToHClip(o.positionVS);
o.screenPos = ComputeScreenPos(o.positionCS);
return o;
}
//fixed4 frag(v2f i) : SV_TARGET
//片元着色器
half4 frag(Varyings i) : SV_TARGET
{
//深度图
//float2 uv = i.screenPos.xy / i.screenPos.w;
float2 uv = i.positionCS.xy/ _ScreenParams.xy;
float4 cameraDepthTex = SAMPLE_TEXTURE2D(_CameraDepthTexture,sampler_CameraDepthTexture,uv);
float depthTex = LinearEyeDepth(cameraDepthTex,_ZBufferParams);
float depth = depthTex + i.positionVS.z;
float4 highLight = 1 - depth;
highLight = pow(highLight,_HighLightFade);
highLight *= _HighLightColor;
return highLight;
}
ENDHLSL
}
}
}