I am trying to write a depthmap shader. It works fine when I add this as post processing effect for the whole scene/camera. But when I add this shader to a single object/material it is no longer working.
What I want to achieve is having a material/shader on an object in my scene and the object becomes darker (or lighter) the further away I move from this object.
Maybe the _CameraDepthTexture is not working for single objects or some minor code changes?
If it’s on an existing object in the scene, you don’t need to read the depth texture at all. You can just use the depth value the object itself already knows.
This should give you the exact same results you got with the post process when placed on a mesh in the scene. depth = pow(Linear01Depth(i.pos.z), .85);
another thing: If I use the “i.vertex.z” value do calculate things I have different outputs in editor and play mode in unity… for example: I set objects to become black if z-value > 500. In the editor they become black when I move away just a little, when I press Play and start the game they become black much later. What could this be?
The SV_POSITION’s .z in the fragment shader is the Z depth. The same depth value that’s stored in the depth texture. So the depth related functions you’d use on the depth texture work on that value just as well.
For perspective projections, the depth is non-linear, meaning 0.5 isn’t halfway between the near and clip planes. The Linear01Depth() function transforms into a linear one so that 0.0 is the near plane, 1.0 is the far plane, and 0.5 is halfway between those two.
The scene view uses a dynamic near and far plane depending on what you’re looking at. When you press F to focus on an object, it’ll adjust those values to ensure the selection is fully visible. Or you can override the near and far plane in the scene view’s camera settings, accessible via the camera icon in the top right of that window. The game view uses a fixed near and far plane, which is whatever is set on the active camera game object being used to render from.
For perspective projections, the ComputeScreenPos() output .w is the linear view space depth. It also happens to be the clip space’s .w too, so it’s the value you’d get from o.vertex.w in the vertex shader, and also still i.vertex.w in the fragment shader (the xyz values do not match between the vertex and fragment though).