這是一個基於GLUT的快速和骯髒的C++程序,用於繪製兩個長方形的平面紅色背景上的藍色和綠色的C++程序。按'a'或'z'使它們沿着X軸在任一方向上進行軌道運動。我的問題是,如果我啓用GL_DEPTH_TEST,它有時繪製一個矩形,有時是兩個或有時只是背景,但從未正確使用較近的多邊形遮蔽較遠一個的一些或全部部分。不設置GL_DEPTH_TEST只是使多邊形以繪圖順序顯示。OpenGL多邊形z緩衝區問題
下面的代碼有什麼問題?
#include <windows.h>
#include <GL/gl.h>
#include <GL/glu.h>
#include <GL/glut.h>
#include <cmath>
#pragma comment(lib, "opengl32.lib")
#pragma comment(lib, "glu32.lib")
int angle = 0;
void oglDraw()
{
angle += 360;
angle %= 360;
float fAngle = angle/(180/3.14159);
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
gluPerspective(90, 1, 0, 10);
gluLookAt(0, 0, -1, 0, 0, 1, 0, 1, 0);
float yFactor = 1;
float zFactor = 1;
float y = yFactor * sin(fAngle);
float z = 1 + zFactor - cos(fAngle) * zFactor;
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
glClearColor(1, 0, 0, 1);
glPolygonMode(GL_FRONT, GL_FILL);
glBegin(GL_POLYGON);
glColor4f(0, 0, 1, 1);
glVertex3f(-1.0, y-1.0, z);
glVertex3f(+1.0, y-1.0, z);
glVertex3f(+1.0, y+1.0, z);
glVertex3f(-1.0, y+1.0, z);
glEnd();
fAngle = (180 - angle)/(180/3.14159);
y = -yFactor * sin(fAngle);
z = 1 + zFactor - cos(fAngle) * zFactor;
glBegin(GL_POLYGON);
glColor4f(0, 1, 0, 1);
glVertex3f(-1.0, y-1.0, z);
glVertex3f(+1.0, y-1.0, z);
glVertex3f(+1.0, y+1.0, z);
glVertex3f(-1.0, y+1.0, z);
glEnd();
glFlush();
glutSwapBuffers();
}
//////////////////////////////////////////////////////////////////////////
void oglKeyboard(byte ch, int x, int y)
{
if(ch == 'z')
{
angle++;
glutPostRedisplay();
}
else
if(ch == 'a')
{
angle--;
glutPostRedisplay();
}
}
//////////////////////////////////////////////////////////////////////////
int main(int argc, char **argv)
{
glutInit(&argc, argv);
glutInitDisplayMode(GLUT_RGB | GLUT_DOUBLE | GLUT_DEPTH);
glutInitWindowSize(1024, 768);
glutCreateWindow("OGL test");
gluOrtho2D(0, 1024, 768, 0);
glEnable(GL_DEPTH_TEST);
glutDisplayFunc(oglDraw);
glutKeyboardFunc(oglKeyboard);
glutMainLoop();
}
無關的評論:你應該在模型視圖矩陣使用'gluLookAt'(其中配置您的視圖(相機位置和方向))和而不是投影矩陣。投影矩陣僅用於像gluPerspective,glFrustum和glOrtho這樣的配置您的投影(攝像機鏡頭)。 – 2011-05-23 14:09:57