Alpha Gradient over mesh geometry in shader code

have this scene and for the half transparent box geometry I want to create a shader that gradually reduced the alpha value of gl_FragColor going over the long axis (in this case the z axis in three js).

I am a bit at a loss on how to do that. I thought I could do that with UVs but they run along the wrong axis.

I basically need a way to find out at which percentage point I am on the z axis relative to the mesh size.

Is that even possible in a shader?

I could also send the length size via a uniform. But then again, I missing the overall concept on how to reach the goal. Any help would be greatly appreciated.

Passing in the length as a uniform sounds like a good way to go.

Then you can pass the vertex world space (or model space) position into the fragment shader as a varying and check it against you length value.

A slightly more complex/general approach would be to pass the geometry.boundingBox.min, and geometry.boundingBox.max as 2 uniforms… and do your logic with the vertex coordinate in modelspace.

like maybe in the vertex shader:

varying vec3 normalizedVertex;
...
normalizedVertex = (position - uMin) / (uMax-uMin);

then in the fragment shader you’ll have a simple value going from 0 to 1 on each axis to use for your determination…
like:

gl_FragColor.a = normalizedVertex.z;
2 Likes

That did the trick, thank you so much!

1 Like