OpenGL 中的三角形

Triangle in OpenGL

我正在尝试使用 OpenGL 创建一个三角形,但我在屏幕上只看到一块白板。

这是我的代码:

#include <GL/glut.h>

extern float vertices[3][3] = 
{
    { -0.5f, -0.5f, 0.0f },
    {  0.5f, -0.5f, 0.0f },
    {  0.0f,  0.5f, 0.0f }
};


void display()
{
    glClearColor(0, 0, 0, 1);
    glBegin(GL_TRIANGLES);
    glColor3fv(1, 0, 0);
    glVertex3fv(vertices[0]);
    glVertex3fv(vertices[1]);
    glVertex3fv(vertices[2]);
    glEnd();
    glFlush();
}


int main(int argc, char** argv)
{
    glutInit(&argc, argv);
    glutInitDisplayMode(GLUT_RGBA | GLUT_DEPTH | GLUT_DOUBLE);
    glutInitWindowSize(1000, 1000);
    glutInitWindowPosition(0, 0);
    glutCreateWindow("Hello Gult");
    glutDisplayFunc(display);
    glEnable(GL_DEPTH_TEST);
    glutMainLoop();
    return 0;
}

可能是什么问题,我该如何解决?

在使用 3 个单独的参数指定颜色时,您需要调用 glutSwapBuffers when using a double-buffered window (GLUT_DOUBLE). Also, you must clear the depth buffer when the Depth Test is enabled. Use glColor3f 而不是 glColor3fv

void display()
{
    glClearColor(0, 0, 0, 1);
    glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
    glBegin(GL_TRIANGLES);
    glColor3f(1, 0, 0);
    glVertex3fv(vertices[0]);
    glVertex3fv(vertices[1]);
    glVertex3fv(vertices[2]);
    glEnd();
    glutSwapBuffers();
}