因此,最後我得到了答案。 它需要添加幾行代碼。
在初始化步驟
glClearDepth(1.0F)添加低於3線; glDepthFunc(GL_LESS); glEnable(GL_DEPTH_TEST);
初始化顯示模式添加深度信息(GLUT_DEPTH),如下
glutInitDisplayMode(GLUT_DEPTH | GLUT_DOUBLE | GLUT_RGB);
下面是顯示一個矩形的完整代碼,後面是一個traingle。
#include <GL/glut.h>
#include <stdlib.h>
#include <math.h>
#include<iostream>
using namespace std;
void FPS(void);
GLint gFramesPerSecond = 0;
int TIMER_SPEED = 10000;
float i = 40;
void display(void)
{
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
glLoadIdentity();
gluLookAt(10, 10, i-=.2, 10, 10, -10, 0, 1, 0);
glBegin(GL_LINES);
glColor3f(1, 0, 0);
glVertex3f(0, 0, 0); glVertex3f(20, 0, 0);
glColor3f(0, 1, 0);
glVertex3f(0, 0, 0); glVertex3f(0, 20, 0);
glColor3f(0, 0, 1);
glVertex3f(0, 0, 0); glVertex3f(0, 0, 50);
glEnd();
glBegin(GL_QUADS);
glColor3f(1, 1, 1);
glVertex3f(10, 10, 10); glVertex3f(20, 10, 15); glVertex3f(20, 20, 15); glVertex3f(10, 20, 15);
glEnd();
glBegin(GL_TRIANGLES);
glColor3f(0, 1, 0);
glVertex3f(12, 12, 20);
glVertex3f(22, 14, 12);
glVertex3f(16, 22, 12);
glEnd();
glutSwapBuffers();
}
void timer(int v)
{
static GLfloat u = 0.0;
u += 0.01;
glutTimerFunc(TIMER_SPEED/60.0, timer, ++v);
display();
}
void Init(void)
{
glClearColor(0.0, 0.0, 0.0, 0.0);
glClearDepth(1.0f);
glDepthFunc(GL_LESS);
glEnable(GL_DEPTH_TEST);
}
void Resize(int width, int height)
{
glViewport(0, 0, width, height);
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
glFrustum(-15, 30, -15, 30, 15, 40);
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
}
int main(int argc, char **argv)
{
glutInit(&argc, argv);
glutInitDisplayMode(GLUT_DEPTH | GLUT_DOUBLE | GLUT_RGB);
glutInitWindowSize(640, 480);
glutInitWindowPosition(200, 200);
glutCreateWindow("3D Object in OpenGL");
glutKeyboardFunc(myKeyboard);
Init();
glutDisplayFunc(display);
glutReshapeFunc(Resize);
glutTimerFunc(100, timer, 0);
glutMainLoop();
return 0;
}
完全同意..它是可見的表面檢測問題..現在如何使用深度測試得到正確的結果? – Bhupendra