Search code examples
c++openglglut

How can i draw two object in the same window in openGL c++?


I'm trying to draw 2 different objects in Visual Studio using OpenGL. I can't seem to draw both object at the same time in the same window. I Tried putting both object in the same function, but it only display one object in the window.

#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();

}

As you can see void kapal() is the first object and void mobil() is the second.

This the result that i got:

This the result that i got

Is there anyway to fix this so i can display both objects in the same windows?


Solution

  • The issue is that you call glClear(GL_COLOR_BUFFER_BIT); before drawing an object. Clear the framebuffer before drawing anything, but not before drawing a specific object.

    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
    
        // [...]
    }