Adam
Adam

Reputation: 33

Tying to create a background in OpenGL

I'm trying to create a background in an OpenGL game. This is based on freeglut and OpenGL immediate mode (due to requirements). My issue is that I cannot get the background image to display correctly, it appears as a thin strip rotating with my camera. This leads me to believe it is a positioning issue but I have tried changing all the Z positions of objects. Below is my render function which I want to draw the background and then the player "mSpaceShip"

For some context SCREEN_WIDTH = 1200 SCREEN_HEIGHT = 1200

void GameInstance::Render()
{
    glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

    glMatrixMode(GL_PROJECTION);
    glPushMatrix();
    glLoadIdentity();
    gluOrtho2D(-SCREEN_WIDTH / 2, SCREEN_WIDTH / 2, -SCREEN_HEIGHT / 2, SCREEN_HEIGHT / 2);
    glMatrixMode(GL_MODELVIEW);

    glPushMatrix();
    glTranslatef(0.0f, 0.0f, 100.0f);
    glBegin(GL_QUADS);
    glVertex2i(0, 0);
    glVertex2i(SCREEN_WIDTH, 0);
    glVertex2i(SCREEN_WIDTH, SCREEN_HEIGHT);
    glVertex2i(0, SCREEN_HEIGHT);
    glEnd();
    glPopMatrix();

    glMatrixMode(GL_PROJECTION);
    glPopMatrix();
    glMatrixMode(GL_MODELVIEW);



    mSpaceShip->Render();

    //for (int i = 0; i < 500; i++) {
    //  cubeField[i]->Draw();
    //}

    glFlush();
    glutSwapBuffers();
}

Upvotes: 2

Views: 77

Answers (1)

S. McPharlin
S. McPharlin

Reputation: 98

Try not to over-complicate things for yourself.

void GameInstance::Render()
{
    glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

    // the default matricies set the origin to be at the center of the screen, with
    // (-1, -1) being at the bottom-left corner, and
    // ( 1,  1) being at the top-right.

    glMatrixMode(GL_PROJECTION);
    glPushMatrix();
    glLoadIdentity();
    glMatrixMode(GL_MODELVIEW);
    glPushMatrix();
    glLoadIdentity();

    // render a full-screen quad without writing to the depth buffer

    glDisable(GL_DEPTH_TEST);
    glBegin(GL_QUADS);
        glVertex2i(-1, -1);
        glVertex2i( 1, -1);
        glVertex2i( 1,  1);
        glVertex2i(-1,  1);
    glEnd();
    glEnable(GL_DEPTH_TEST);

    glMatrixMode(GL_PROJECTION);
    glPopMatrix();
    glMatrixMode(GL_MODELVIEW);
    glPopMatrix();

    mSpaceShip->Render();

    glFlush();
    glutSwapBuffers();
}

In your call to gluOrtho2D, you were setting the origin to be at the center of the screen, but only rendering the quad within the upper-right quadrant (but as you're making changes to GL_MODELVIEW outside of Render(), this is just a guess).

Using gluOrtho2D is equivalent to calling glOrtho with the z-clipping range set to [-1 .. 1], so I suspect that your call to glTranslatef needed a much smaller z-value, like 0.5f instead of 100.0f.

Upvotes: 2

Related Questions