0 votes

I can't understand the role of DEPTH_TEXTURE, because I always get "1.0".

float depth = texture(DEPTH_TEXTURE, SCREEN_UV).x;

I want to get the distance between the pixel and the screen in the fragment. I always thought that DEPTH_TEXTURE is what I want. I found VERTEX is what I want ´╝îbecause It's the position of the pixel in the camera coordinate space.

Am i wrong about DEPTH_TEXTURE and VERTEX in fragment? I 'm very confused now.
Also, are they similar?

in Engine by (206 points)

1 Answer

+1 vote
Best answer

You should be able to get the distance by converting VERTEX from (local) ModelView space to view space. The z-coordinate of the resulting Vector3 should be the (negative) "parallel" distance to the view plane. You could also use the length of the Vector if you want the distance to the screen center.

Such a calculation should usually be done in the vertext() part and the result then passed (& automatically interpolated) via a "Varying" to the fragment() shader.
Roughly like this:

shader_type spatial;

varying float z_dist;

void vertex() {
   z_dist = clamp((MODELVIEW_MATRIX * vec4(VERTEX, 1.0)).z * -1.0,0.0,50.0);

void fragment() { 
  ALBEDO = vec3(z_dist/50.0,0.1,50.0-(z_dist/50.0));

The example varies the color depending on the camera distance. The color in this example is only varied in the z-range of 0-50.

You'll find examples about the DEPTH_TEXTURE here:
But I've read about issues when using it on mobile (Android) targets with the standard settings.

by (3,252 points)
selected by

Oh, I just realized that it is even simpler.
VERTEX (by default) is already automatically transformed into view space in the fragment part. (I think this is a bit inconsistent in terms of naming but anyway...)

So the distance to the camera inside the fragment shader simply is VERTEX.z. multiply by -1 if you need a positive value for vertices in view.

Or length(VERTEX) will be the distance from screen center.

One thing about DEPTHTEXTURE.
To my knowledge that is more useful for i.e. screen reading shaders where no access to the VERTEX is possible. In that case you can calculate from a DEPTH
TEXTURE lookup back to an (approximated) z-depth.

Thank you, this helped me eliminate my confusion

Welcome to Godot Engine Q&A, where you can ask questions and receive answers from other members of the community.

Please make sure to read How to use this Q&A? before posting your first questions.
Social login is currently unavailable. If you've previously logged in with a Facebook or GitHub account, use the I forgot my password link in the login box to set a password for your account. If you still can't access your account, send an email to webmaster@godotengine.org with your username.