仅显示 OpenGL 最近的顶点绘制

OpenGL only most recent vertex draw displayed

本文关键字:顶点 绘制 最近 显示 OpenGL      更新时间:2023-10-16

OpenGL的新手,尝试使用矩形绘制函数分别绘制2个矩形。 使用 openGL 3、GLFW 和 GLEW。 我做了一个名为drawBox的函数来绘制一个矩形。我的问题是,如果我在主循环中多次调用它,则只显示绘制的最后一个矩形。

void drawBox(float x, float y, float w, float h, float r, float g, float b) {
GLfloat colours[15], vertices[10] = {
    x, y,
    x, y + h,
    x + w, y + h,
    x + w, y,
    x, y
};
for(int i = 0; i < 5; ++i) {
    colours[3*i] = (GLfloat)r;
    colours[3*i + 1] = (GLfloat)g;
    colours[3*i + 2] = (GLfloat)b;
}
GLuint buff[2];
glGenBuffers(2, buff);
glBindBuffer(GL_ARRAY_BUFFER, buff[1]); 
glBufferData(GL_ARRAY_BUFFER, 15*sizeof(GLfloat), colours, GL_STREAM_DRAW); 
glVertexAttribPointer(1, 3, GL_FLOAT, GL_FALSE, 0, (void*)0);
glEnableVertexAttribArray(1);
glBindBuffer(GL_ARRAY_BUFFER, buff[0]); 
glBufferData(GL_ARRAY_BUFFER, 10*sizeof(GLfloat), vertices, GL_STREAM_DRAW); 
glVertexAttribPointer(0, 2, GL_FLOAT, GL_FALSE, 0, (void*)0);
glEnableVertexAttribArray(0);
glClear( GL_COLOR_BUFFER_BIT );
glUseProgram(defaultShader);
glDrawArrays(GL_TRIANGLE_STRIP, 0, 5);        
glDisableVertexAttribArray(0);
glDisableVertexAttribArray(1);
glDeleteBuffers(2, buff);
} 

我需要更改什么才能使此函数显示矩形,而不管过去的绘制如何。 假设所有 z 指数均为 0,并且永远不会发生重叠。 假设我可能必须对drawBox进行drawCircle调用或drawTriangle或介于2次调用之间的东西。

您应该在所有draw*()调用之前只调用glClear( GL_COLOR_BUFFER_BIT );一次。