TUTORIAL 1 - OpenGL Fundamentals

1  2  3  4  5  6  7  8  9  10  11  12  13

3D-Drawing and Animation with OpenGL

Extending the 2D-drawing program to 3D-drawing is pretty simple: we just have to add the z?coordinate. As an example we will implement a rotating pyramid.

In principle we could draw 4 triangles and a rectangle as bottom, but OpenGL offers much more suitable primitives. If we take a look at the different primitives, we see, that the GL_TRIANGLE_FAN is much more suitable.

When we use the GL_TRIANGLE_FAN for the pyramid, it is important to specify the first point again as last point to draw the last triangle and therefore close the triangle fan. Therefore the code for drawing the pyramid would look like this:

   glBegin(GL_TRIANGLE_FAN);     	// draw triangle
      glColor3f(1.0f,0.0f,0.0f);                	// set color to red
      glVertex3f(  0.0f,  30.0f, 0.0f);
      glColor3f(0.0f,1.0f,0.0f);                	// set color to green
      glVertex3f(-50.0f, -50.0f, 50.0f);
      glColor3f(1.0f,1.0f,0.0f);                	// set color to yellow
      glVertex3f( 50.0f, -50.0f, 50.0f);
      glColor3f(0.0f,0.0f,1.0f);                	// set color to blue
      glVertex3f( 50.0f, -50.0f, -50.0f);
      glColor3f(1.0f,1.0f,1.0f);                	// set color to white
      glVertex3f( -50.0f, -50.0f, -50.0f);
      glColor3f(0.0f,1.0f,0.0f);                	// set color to green
      glVertex3f(-50.0f, -50.0f, 50.0f);
   glEnd();
   glBegin(GL_QUADS);                           	// draw square
      glColor3f(0.0f,1.0f,0.0f);                	// set color to green
      glVertex3f(-50.0f, -50.0f, 50.0f);
      glColor3f(1.0f,1.0f,1.0f);                	// set color to white
      glVertex3f( -50.0f, -50.0f, -50.0f);
      glColor3f(0.0f,0.0f,1.0f);                	// set color to blue
      glVertex3f( 50.0f, -50.0f, -50.0f);
      glColor3f(1.0f,1.0f,0.0f);                	// set color to yellow
      glVertex3f( 50.0f, -50.0f, 50.0f);
   glEnd();

To animate the pyramid, we have to do almost nothing: we only use the glRotatef command and change the angle. This command has four parameters, where the first parameter gives the rotation angle, while the next three parameters specify the x-, y- and z-component of the rotation vector. If we want to realize more complex movements, we can combine multiple glRotatef and glTranslatef commands. If we want to rotate the pyramid along the x- and y-axis, the code could look like this:

   alpha+=0.2;
   beta+=0.1;
   glLoadIdentity();
   glRotatef(alpha,0.0f,1.0f,0.0f);             	// rotate around y-axis
   glRotatef(beta,1.0f,0.0f,0.0f);              	// rotate around x-axis

With these few changes, we now have a rotating pyramid.

previous   next