PDA

View Full Version : simple opengl



zuyaking
07-03-2013, 03:31 AM
Hi!
I am new to opengl and i have tried doing some simple stuff in it, but it seems i got stuck here.
This code should draw a few cuboids and move up z so I can like "walk thrugh" those cuboids.
But when i start the program there are just 2 rectangles blinking on the screen.

#include <GL/gl.h>
#include <GL/glut.h>





float z=0;

void init()
{
glClearColor(0,0,0,0);
}


void drawBasic(float x, float y, float ze)
{
glClear(GL_COLOR_BUFFER_BIT);
glLoadIdentity();

glPushMatrix();
//glRotatef(angle,0,1,0);
ze=z;
glBegin(GL_QUADS);
//front
glVertex3f(x-0.4f, y-0.7f, ze);
glVertex3f(x-0.4f, y+0.7f, ze);
glVertex3f(x+0.4f, y+0.7f, ze);
glVertex3f(x+0.4f, y-0.7f, ze);
//right
glVertex3f(x+0.4f, y-0.7f, ze);
glVertex3f(x+0.4f, y+0.7f, ze);
glVertex3f(x+0.4f, y+0.7f, ze-0.4f);
glVertex3f(x+0.4f, y-0.7f, ze-0.4f);
//back
glVertex3f(x-0.4f, y-0.7f, ze-0.4f);
glVertex3f(x-0.4f, y+0.7f, ze-0.4f);
glVertex3f(x+0.4f, y+0.7f, ze-0.4f);
glVertex3f(x+0.4f, y-0.7f, ze-0.4f);
//left
glVertex3f(x-0.4f, y-0.7f, ze);
glVertex3f(x-0.4f, y-0.7f, ze-0.4f);
glVertex3f(x-0.4f, y+0.7f, ze-0.4f);
glVertex3f(x-0.4f, y+0.7f, ze);

glEnd();
glPopMatrix();

glutSwapBuffers();
}

void display()
{
drawBasic(-0.5,0,z);
drawBasic(0.5,0,z);
drawBasic(-0.5,0,z-1.4);
drawBasic(0.5,0,z-1.4);
drawBasic(-0.5,0,z-2.8);
drawBasic(0.5,0,z-2.8);
drawBasic(-0.5,0,z-4.2);
drawBasic(0.5,0,z-4.2);
}

void update(int val)
{
z+=0.01;

if(z>5)
{
z=0;
}

glutPostRedisplay();
glutTimerFunc( 20, update, 0);
}


int main(int argc, char **argv)
{
glutInit(&argc, argv);
glutInitDisplayMode(GLUT_RGB | GLUT_DOUBLE | GLUT_DEPTH );

glutInitWindowSize(800, 600);
glutCreateWindow("simple");

init();

glutDisplayFunc(display);
glutTimerFunc(1, update, 0);

glutMainLoop();
return 0;
}

Please help!

Carmine
07-03-2013, 10:00 AM
You never explicitly define a projection matrix which means you are using the default, which is orthographic looking down the -Z axis. IF your quads are between the clipping planes (z = +1, z = -1), you will only see a rectangle. But you are translating your object far beyond the forward clipping plane (z = 5), so you'll only be able to see it when -1 < z < +1. Try changing 'if (z > 5) to 'if (z > 1)'. This should make the rectangles visible all the time.

In an orthographic projection objects do not change size when they move towards and away from the camera. For that to happen, you must define a perspective projection. Google glMatrixMode and gluPerspective to see how this is done. Look for examples of code to see how to implement these commands.

zuyaking
07-03-2013, 12:07 PM
I got it!
Thanks a lot.