如何解决无法统一采样相机深度纹理
我是 Unity 中的着色器编码的新手(实际上是一般的着色器)。我最近一直在尝试通过对深度纹理进行采样并使用它在渲染视图和恒定颜色之间进行混合来创建基本的雾效果,但是我无法从深度纹理中获取信息。
据我所知,以下代码应该简单地在应用了此材质的任何对象的屏幕空间中显示深度纹理,但是我的测试对象仅显示无阴影的纯灰色。我也做了一些其他测试,我认为正在发生的是,当我尝试从深度纹理中采样时,它总是返回 0.5 秒的 fixed4,但我不明白为什么。
我知道我可能在这里犯了一些搞笑的菜鸟错误,但我是菜鸟,所以任何帮助都将不胜感激。谢谢
Shader "Hidden/Atmosphere"
{
Properties
{
_MainTex ("Texture",2D) = "white" {}
_Scale ("Scale",float) = 1
}
SubShader
{
// No culling or depth
Cull Off ZWrite Off ZTest Always
GrabPass{"_Post"}
Pass
{
CGPROGRAM
#pragma vertex vert
#pragma fragment frag
#include "UnityCG.cginc"
struct appdata
{
float4 vertex : POSITION;
};
struct v2f
{
float4 ScreenPos : TEXCOORD0;
float4 vertex : SV_POSITION;
};
float _Scale;
v2f vert (appdata v)
{
v2f o;
o.vertex = UnityObjectToClipPos(v.vertex);
o.ScreenPos = ComputeScreenPos(o.vertex);
return o;
}
sampler2D _Post;
sampler2D _CameraDepthTexture;
fixed4 frag (v2f i) : SV_Target
{
float2 ScreenspaceUV = i.ScreenPos.xy/ i.ScreenPos.w;
//fixed4 col = tex2D(_Post,ScreenspaceUV);
fixed4 col = tex2D(_CameraDepthTexture,ScreenspaceUV);
//col = fixed4(i.ScreenPos.x/i.ScreenPos.w,i.ScreenPos.y/i.ScreenPos.w,1);
//col.rgb = 1 - col.rgb;
return col;
}
ENDCG
}
}
}
解决方法
我试图达到完全相同的效果,但遇到了完全相同的问题。
第一步是将主相机depthTextureMode设置为DepthTextureMode.Depth。 为此,请在脚本的 Awake 方法中编写以下代码:
if(Camera.main.depthTextureMode != DepthTextureMode.Depth)
Camera.main.depthTextureMode = DepthTextureMode.Depth;
现在,如果您点击播放,使用您的自定义着色器的对象将不会出现在相机中。事实证明,如果您使用自定义着色器,则必须定义额外的 ShadowCaster 通道以写入该 depthTexture。
第二步是将此通道作为单独的通道添加到您的自定义着色器中(!!不是您用于渲染雾的着色器。场景中的对象使用的着色器!!).
Pass
{
Name "ShadowCaster"
Tags { "LightMode" = "ShadowCaster" }
Fog {Mode Off}
ZWrite On ZTest LEqual Cull Off
Offset 1,1
CGPROGRAM
#pragma vertex vert
#pragma fragment frag
#pragma multi_compile_shadowcaster
#include "UnityCG.cginc"
struct v2f
{
V2F_SHADOW_CASTER;
};
v2f vert( appdata_base v )
{
v2f o;
TRANSFER_SHADOW_CASTER(o)
return o;
}
float4 frag( v2f i ) : SV_Target
{
SHADOW_CASTER_FRAGMENT(i)
}
ENDCG
}
你应该没事了。
!!还有一个重要的通知!!如果您的着色器的渲染队列高于 2500,则对象将不会影响 depthTexture,因此您将看不到它!!
https://forum.unity.com/threads/custom-shader-not-writing-to-depth-buffer.1048934/ https://forum.unity.com/threads/multiple-cameras-depth-buffer-incorrect-in-shader.763802/
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。