Calculating Depth

I am trying to retrieve depth it seems that there’s two way to do it, manually and using the _CameraDepthNormalsTexture.

Using _CameraDepthNormalsTexture, I can’t simply get any result.

Using the manual way I am having nice results but I am still facing some difficulties.

o.depth = -mul(UNITY_MATRIX_MV, v.vertex).z * _ProjectionParams.w;

With this formula, I have a nice result but it is link with the Camera clipping planes which is a bit annoying.

o.depth = 1.0 / (_ProjectionParams.x * -mul(UNITY_MATRIX_MV, v.vertex).z + _ProjectionParams.y);

With this forumula, the depth is no more related to the camera clipping planes but to the camera position… which is worse.

Is there a better way to retrieve depth ?
Thanks a lot !

Any idea ?

That might be because you’re using the forward rendering path. Only the deferred path fills _CameraDepthNormalsTexture.

I’d say you could just do this:

o.depth = mul(UNITY_MATRIX_MV, v.vertex).z * _ProjectionParams.x;

The w component is 1/farClip, so yes, then it’s linked with the far clipping plane. The x component just inverts if needed.

Another approach is to just take distance instead of depth.

o.depth = distance(mul(_Object2World, v.vertex), _WorldSpaceCameraPos);

Thank you @jvo3dc :slight_smile: