我正在尝试使用OpenGL在Visual Studio中绘制2个不同的对象。我似乎无法在同一窗口中同时绘制两个对象。我尝试将两个对象放在相同的函数中,但只在窗口中显示一个对象。
#include<Windows.h>
#include<glut.h>
#include<stdlib.h>
#include<iostream>
using namespace std;
void init()
{
glClearColor(0, 0.4, 1, 0.0);
glMatrixMode(GL_PROJECTION);
gluOrtho2D(0.0, 800, 0.0, 600);
}
void kapal()
{
//badan
glClear(GL_COLOR_BUFFER_BIT);
glBegin(GL_POLYGON);
glColor3ub(148, 111, 70);
glVertex2i(20 , 100);
glVertex2i(160 , 100);
glColor3ub(107, 65, 17);
glVertex2i(140 , 60 );
glVertex2i(40 , 60);
glColor3ub(9, 5, 0);
glEnd();
//tiang
glColor3ub(97, 65, 28);
glLineWidth(5);
glBegin(GL_LINES);
glVertex2i(90 ,100 );
glVertex2i(90 , 160 );
glEnd();
//layar
glColor3ub(215, 215, 215);
glBegin(GL_TRIANGLES);
glVertex2i(90, 160 );
glVertex2i(120 , 130 );
glVertex2i(90 , 130);
glEnd();
glFlush();
}
void mobil()
{
//bawah
glClear(GL_COLOR_BUFFER_BIT);
glBegin(GL_POLYGON);
glColor3ub(148, 111, 70);
glVertex2i(100, 170);
glVertex2i(100, 230);
glVertex2i(450, 230);
glVertex2i(450, 170);
glEnd();
//atas
glBegin(GL_POLYGON);
glColor3ub(148, 111, 70);
glVertex2i(150, 230);
glVertex2i(200, 270);
glVertex2i(400, 270);
glVertex2i(450, 230);
glEnd();
glFlush();
}
static void display(void)
{
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
kapal();
mobil();
glutSwapBuffers();
}
int main(int argc, char** argv)
{
glutInit(&argc, argv);
glutInitDisplayMode(GLUT_SINGLE | GLUT_RGB);
glutInitWindowPosition(100, 100);
glutInitWindowSize(800, 600);
glutCreateWindow("Kapal APi ");
init();
glutDisplayFunc(display);
glutMainLoop();
}
如您所见,void kapal()
是第一个对象,void mobil()
是第二个对象。
这是我得到的结果:
反正有解决此问题的方法,所以我可以在同一窗口中显示两个对象吗?
问题是在绘制对象之前调用glClear(GL_COLOR_BUFFER_BIT);
。在绘制任何内容之前清除帧缓冲区,但在绘制单个对象之前不清除。
static void display(void)
{
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); // <-- this is OK
kapal();
mobil();
glutSwapBuffers();
}
void kapal()
{
//badan
// glClear(GL_COLOR_BUFFER_BIT); <--- DELETE
// [...]
}
void mobil()
{
//bawah
// glClear(GL_COLOR_BUFFER_BIT); <--- DELETE
// [...]
}