I'm writing an OpenGL ES 2.0 game (on iOS). How can I create a shader (since I assume this would be simpler to do in a shader) so that geometry further from the origin (on the Z axis) appears darker?
The water in this image illustrates the effect I have in mind
(source: bytecellar.com)
This is fairly simple to do if you just want to use the Z position of your geometry. You could have a vertex shader like the following:
attribute vec4 position;
varying float zDepth;
uniform mat4 modelViewProjMatrix;
void main()
{
vec4 newPosition = modelViewProjMatrix * position;
gl_Position = newPosition;
zDepth = (2.0 - (1.0 + newPosition.z))/2.0;
}
and a fragment shader like
varying highp float zDepth;
void main()
{
gl_FragColor = vec4(zDepth, zDepth, 0.0, 1.0);
}
which would produce the following look:
I have an example of this within this iPad sample code I assembled for my OpenGL ES 2.0 class.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With