简体   繁体   中英

How can I colour things in OpenGL ES 2.0 based on their depth?

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

Zarch
(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:

深度阴影的OpenGL茶壶

I have an example of this within this iPad sample code I assembled for my OpenGL ES 2.0 class.

I did a rather interesting test with what @brad provide. I just change the line:

gl_FragColor = vec4(1.0, 1.0, 0.0, zDepth);

Nothing happen to the alpha. Is it me or is there something else is missing as for the Alpha ?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM