在对象前面绘制的更远的物体(openGL)

时间:2014-01-10 06:06:47

标签: opengl

主要功能:

int _tmain(int argc, char* argv[])
{
glutInit(&argc, argv);
glutInitWindowSize (500, 500);

glutInitDisplayMode (GLUT_RGB | GLUT_DOUBLE | GLUT_DEPTH );
glEnable(GL_DEPTH_TEST); 

glDepthFunc(GL_LESS);
glutInitWindowPosition (700, 100);
glutCreateWindow("Result");
glutDisplayFunc(display2);  
glutReshapeFunc(reshape2);
glutMouseFunc(main_mouse);
glutKeyboardFunc(keyboard);
glutMainLoop();

return 0;
}

Display2功能:

void display2()
{   
glClearColor(1.0,1.0,1.0,1.0);
glClear(GL_COLOR_BUFFER_BIT|GL_DEPTH_BUFFER_BIT);

glMatrixMode(GL_MODELVIEW);

glLoadIdentity();

//Green square
glColor3f(0.0,1.0,0.0);
glBegin(GL_POLYGON);
glVertex3f(0.5,0.5,-1.0);
glVertex3f(0.5,1.5,-1.0);
glVertex3f(1.5,1.5,-1.0);
glVertex3f(1.5,0.5,-1.0);
glEnd();

//Red square
glColor3f(1.0,0.0,0.0);
glBegin(GL_POLYGON);
glVertex3f(0.0,0.0,-2.0);
glVertex3f(0.0,1.0,-2.0);
glVertex3f(1.0,1.0,-2.0);
glVertex3f(1.0,0.0,-2.0);
glEnd();

glutSwapBuffers();
}

reshape2功能

void reshape2(int width, int height)
{
glViewport(0,0,width,height);

glMatrixMode(GL_PROJECTION);

glOrtho(-3.0,3.0,-3.0,3.0,0.01,3.0);
}

我在openGL中遇到深度缓冲问题。我尝试绘制2平方红色和绿色。红色的一个位于绿色的后面。 红色方块的z值为-2,而绿色方块的z值为-1。但红色正方形显示在绿色广场前面。我已启用深度测试,但仍无法正常工作。我的计划有什么问题?

1 个答案:

答案 0 :(得分:3)

在致电gl*之前,请勿拨打任何glutCreateWindow功能,因此请在glEnable之后移动glDepthFunc

每个gl函数都会调用仅使用GLUT窗口创建的上下文。在此之前,没有OpenGL功能有效。