问题描述
我正在尝试使用OpenGL ES 2在3D环境中渲染2D(平面)子图形.创建每个子图形的方式非常标准:我创建了一个由两个三角形组成的四边形,然后将纹理映射到该三角形上.一切正常,除了我注意到一些奇怪的事情:深度测试(应在3D模式下)打开时,我的精灵的角使用背景色绘制.
I am trying to render 2D (flat) sprites in a 3D environment using OpenGL ES 2. The way I create each sprite is pretty standard: I create a quad consisting of two triangles, and I map the texture onto that. Everything works fine, except I noticed something strange: when depth testing is turned on (which it should be in 3D mode), the corners of my sprites are painted using the background color.
最简单的显示方法是通过插图:
The easiest way to show this is by illustration:
当我关闭深度测试(在左侧)时,它看起来不错,但是当我打开它(在右侧)时,您可以看到绿色精灵的矩形重叠在黄色精灵的顶部.它们都使用相同的代码,相同的PNG文件,相同的着色器.除了深度测试外,其他一切都一样.
When I turn off depth testing (on the left) it looks fine, but when I turn it on (on the right) you can see the green sprite's rectangle overlapping on top of the yellow sprite. They both use the same code, the same PNG file, the same shader. Everything is the same except depth testing.
我希望有人可能知道解决此问题的方法.
I'm hoping someone might know a way to work around this.
推荐答案
您可以做的是alpha测试.基本上,纹理的alpha值必须为0(在该位置应该是透明的)(它可能已经具有).然后您配置alpha测试,例如
What you can do is alpha testing. Basically your texture has to have an alpha value of 0 where it should be transparent (which it may already have). Then you configure alpha test like e.g.
glAlphaFunc(GL_GREATER, 0.5f);
glEnable(GL_ALPHA_TEST);
通过这种方式,不会将alpha值
This way every pixel (or better fragment) with an alpha value <= 0.5 will not be written into the framebuffer (and therefore not into the depth buffer). You can also do the alpha test yourself in the fragment shader by just discarding the fragment:
...
if(color.a < 0.5)
discard;
...
那么您就不需要固定功能的alpha测试了(我认为这就是为什么它在现代桌面GL中被弃用的原因,而不是ES).
Then you don't need the fixed-function alpha test (I think that is the reason why it is deprecated in modern desktop GL, don't know about ES).
编辑:研究完ES 2.0规范后,似乎不再有固定功能的alpha测试,因此您必须像上面编写的那样在片段着色器中进行测试.这样,您还可以使其依赖于特定的颜色或任何其他可计算的属性,而不是依赖于Alpha通道.
After looking into the ES 2.0 spec, it seems there is no fixed-function alpha test any more, so you will have to do it in the fragment shader like written above. This way you can also make it dependent on a specific color or any other computable property instead of the alpha channel.
这篇关于精灵四方& OpenGL ES 2中正确进行深度测试的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!