开发者

Background object is drawn in front of foreground object in OpenGL?

For testing purposes let's assume I've draw 2 teapots with glutSolidTeapot(), like this:

glColor3f(1.0f, 0.0f, 0.0f); // Red teapot
glutWireTeapot(1.0f);

glColor3f(0.0f, 1.0f, 0.0f); // Green teapot
glTranslatef(0.0f, 0.0f, 3.0f);
glutWireTeapot(1.0f);

The camera is initially located at (x,y,z) = (0.0f, 0.0f, 5.0f) and I'm looking at z = -1 (this is camera position #1). I'm sure you understand that the green teapot is the closest object to the camera and the red one is behind it. The problem is that the red one is drawn like it's in front of the green one, which doesn't look right:

开发者_开发技巧Example: http://i.stack.imgur.com/8WoEn.png

Now, if I move the camera too (x,y,z) = (0.0f, 0.0f, -5.0f) and look at z = 1 (this is camera position #2), I will see the red teapot in front of the green one, this is normal behavior. The red is now the object closest to the camera and the green one is behind the red one. Everything is fine.

Example: http://i.stack.imgur.com/eJvPE.png

I know this has something to do with the order, if I switch the code above (green teapot code first), than it will fix the problem in the camera position #1, but the problem will now be visible in camera position #2.

Why is this happening and how can I keep the objects behind other objects from being drawn in front, or at all?


You need to allocate a depth-buffer (you're most likely doing this already) and then use glEnable(GL_DEPTH_TEST)

This is happening because without depth-testing, OpenGL does simply not react to different depths relative to the camera. When you enable depth testing, GL will reject all new pixels/fragments that further away than the current closest.

If you want to move around in your scene, you probably want to clear the depth by adding GL_DEPTH_BUFFER_BIT to glClear, or else it will remember the closest fragment from the previous frame.

Other than that, your perspective matrix might be malformed. This is especially likely, since the red teapot is drawn in front of the green one, while you draw them such that the green one would overdraw the red one with correct depth buffering. Hence, the depth values themselves are probably bad.


Probably you haven't enabled Depth Buffer aka z-buffer. To do this in initialization part add something like this

glClearDepth(1.0f);
glEnable(GL_DEPTH_TEST);
glDepthFunc(GL_LEQUAL);

And before rendering every frame you have to clear this buffer as well using

glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

You could check OpenGL Nehe tutorial for more information http://nehe.gamedev.net/data/lessons/lesson.asp?lesson=01

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜