Kamanji Kamanji - 2 months ago 11
C++ Question

openGl object disappears at certain zCoord

I have cube , which i'm trying to move using glTranslatef() function . Everything works great , except that cubeb start disappearing at z>1.

Here is my code

void owidget::initializeGL()
{
glDepthRange(0,100);
glEnable(GL_DEPTH_TEST);
glClearColor(0.0f, 0.0f, 0.0f, 0.0f);
glOrtho(-5.0,5.0,-5.0,5.0,-500.0,500.0);
}

void owidget::paintGL()
{
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
glPushMatrix();
glTranslatef(xPos/100,yPos/100,zPos/100);
glRotatef(xRot,1,0,0);
glRotatef(yRot,0,1,0);
glRotatef(zRot,0,0,1);
cube(0.3);
glPopMatrix(); //Fuction for dislpaying cube
}

void owidget::resizeGL(int width, int height)
{
glViewport(0,0,width,height);
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
}


Here is a picture

Answer

Your setup is a little weird. You're setting zFar in gluPerspective correctly in initializeGL, but it's getting overwritten by glLoadIdentity in paintGL, which resets zFar to the default, which is 1 in Normalized Device Coordinates.

If you change glMatrixMode(GL_PROJECTION); to glMatrixMode(GL_MODELVIEW);, this should work.

I would also recommend defaulting glMatrixMode to GL_MODELVIEW. By this I mean that whenever you're done editing the projection matrix, call glMatrixMode(GL_MODELVIEW);

void owidget::initializeGL()
{   
    glDepthRange(0,100);
    glEnable(GL_DEPTH_TEST);
    glClearColor(0.0f, 0.0f, 0.0f, 0.0f);
    glMatrixMode(GL_PROJECTION);
    gluPerspective(0,650/600,20.0,100.0);
    glMatrixMode(GL_MODELVIEW);
}

void owidget::paintGL()
{
    glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
    glLoadIdentity();
    glPushMatrix();
        glTranslatef(xPos/100,yPos/100,zPos/100);
        glRotatef(xRot,1,0,0);
        glRotatef(yRot,0,1,0);
        glRotatef(zRot,0,0,1);
        cube(0.3);
    glPopMatrix(); //Fuction for dislpaying cube
}

void owidget::resizeGL(int width, int height)
{
    glViewport(0,0,width,height);
    glMatrixMode(GL_PROJECTION);
    glLoadIdentity();
    glMatrixMode(GL_MODELVIEW);
}
Comments