- Home /
Get distance to camera from CameraDepthTexture
I'm working on a fragment shader that runs after the scene has been rendered. In this shader, I need to know the distance of the closest object to the camera. Basically, I need to somehow convert the value in the camera depth texture to a camera distance.
As far as I understand, these two values are similar, but not the same. The camera depth is the distance from the near plane to the object. This means, that if I rotate the camera around its own axis, the depth value for the same point in the scene changes, because the sides of the near plane can get closer to it than the center.
This is how I access the depth:
float cameraDepth = LinearEyeDepth(tex2D(_CameraDepthTexture, screenPos / _ScreenParams.xy));
I'd like to calculate the actual distance to the camera instead, which should not be affected by the rotation of the camera. I have some artifacts in my renderings, which I think are caused by this difference.
Answer by DrummerB · Sep 24, 2020 at 09:04 AM
I think I was able to compute the true distance.
cameraDepth is only an accurate distance at the center of the screen. Points that are on a plane orthogonal to the viewing direction will all have the same camera depth. If we want to convert this into correct distance from the camera, we need to take into account that points that are to the sides of the screen are actually further away than points at the center (with the same camera depth). We need to find the angle between a ray through the current pixel and the view direction.
In view space, this is the arccos of the (normalized) ray direction's z component, because the view direction is (0,0,1). Dividing the camera depth (along the viewing direction) by the cosine of the angle gives the correct camera distance. This can be simplified to:
float cameraDistance = cameraDepth / normalize(viewSpacePos.xyz).z;