Cube disapearing?

I’ve rendered a cube just fine, but as I translate it back or forward, it’ll disapear slowly like drowning into water. Help!

Post your code.

//I’m new to opengGL, so explain to me like
//like I were 3 year old child.

#include <iostream>
#include <gl/glut.h>
using namespace std;

GLfloat rotate;
GLfloat tx, ty, tz;

void init();
void display();
void keyboard(unsigned char key, int x, int y);

void main(int argv, char * argc[])
{
glutInit(&argv, argc);
glutInitDisplayMode(GLUT_DOUBLE | GLUT_RGB | GLUT_DEPTH);
glutCreateWindow(“Cube”);
init();
glutMainLoop();
}

void init()
{
GLfloat light_position[] = {0, 0, -40};
glLightfv(GL_LIGHT0, GL_POSITION, light_position);
glClearColor(0.4, 0.4, 0.4, 0);
glutDisplayFunc(display);
glutKeyboardFunc(keyboard);
glEnable(GL_DEPTH_TEST);
glEnable(GL_LIGHTING);
glEnable(GL_LIGHT0);
glDepthFunc(GL_LESS);
}

void display()
{
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
glLoadIdentity();
glPushMatrix();
glRotatef(rotate, 1, 1, 1);
glTranslatef(tx, ty, tz);
glutSolidCube(1);
glPopMatrix();
glutSwapBuffers();
}

void keyboard(unsigned char key, int x, int y)
{
switch(key)
{
case ‘a’:
tx -= 0.01;
break;
case ‘d’:
tx += 0.01;
break;
case ‘s’:
ty -= 0.01;
break;
case ‘w’:
ty += 0.01;
break;
case ‘q’:
tz += 0.01;
break;
case ‘e’:
tz -= 0.01;
break;
case ‘r’:
rotate += 1;
break;
case ‘\r’:
exit(1);
}
glutPostRedisplay();
}

I don’t see any code to setup the projection matrix, did you leave it out, or you don’t have any? It’s not required, but almost. I believe you move the cube outside the viewing volume, and it get’s clipped.

So how to prevent it from being clipped. Could you rewrite the code for me?

Well, you can’t prevent it from being clipped. But you can modify the code so that it won’t get clipped so fast.

You can try to insert this in the init function.

glMatrixMode(GL_PROJECTION);
glLoadIdentity();
gluPerspective(60, 1, 0.1, 10);
glMatrixMode(GL_MODELVIEW);

This will create a perspective matrix, with 60 degree field of view. 0.1 and 10 is the distance to the near and far clipping plane, the planes clipping your cube (along with four other planes, but don’t worry about them).

You must also insert

glTranslatef(0, 0, -5);

after glRotatef in display(). This is needed because without the above perspective code, the default Z-range is -1 to 1, but with it, it’s 0.1 to 10, so you need to translate it into this range.

Change the values to get a feeling of what they do.

Alter your near and far planes. Your cube is being clipped.

gav

Thanks, guys!