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

依然范特西╮ 提交于 2019-12-06 05:55:58

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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!