Up: OpenGL Wagon examples. Next: 3D example.

Moving wagon example

This is a still shot from the animation. In the animation, wagons continually roll left across the window, with their wheels rotating as they move.

moving_main.h

 1  #include <stdio.h>
 2  #include <GL/glut.h>
 3  #include <math.h>
 4  #include "wagon.h"
   
 5  #define MOVEMENT_RATE 0.0002
   
 6  // Initializes information for drawing within OpenGL.
 7  void init() {
 8      glClearColor(1.0, 1.0, 1.0, 0.0);   // Set window color to white.
 9      glMatrixMode(GL_PROJECTION);        // Set projection parameters.
10      gluOrtho2D(0.0, 3.0, -.25, .75);    // Set viewable coordinates.
11      wagonInit();
12  }
   
13  // Draw a wagon that has traveled across the window the given distance.
14  void drawWagonAt(double dist) {
15      glPushMatrix();
16      glTranslatef(3.0 - dist, 0.0, 0.0);
17      wagonDraw(dist / 0.1);
18      glPopMatrix();
19  }
   
20  // Draws the current image.
21  void draw() {
22      // Compute how far the youngest wagon on-screen has traveled.
23      double offs = fmod(MOVEMENT_RATE * glutGet(GLUT_ELAPSED_TIME), 1.5);
   
24      glClear(GL_COLOR_BUFFER_BIT);   // Clear display window.
   
25      glColor3f(0.0, 0.0, 0.0);
26      drawWagonAt(offs);              // Draw the wagons. (Up to three
27      drawWagonAt(offs + 1.5);        // may be on-screen at once.)
28      drawWagonAt(offs + 3.0);    
   
29      glFlush();  // Process all OpenGL routines as quickly as possible.
30  }
   
31  // Arranges that the window will be redrawn roughly every 40 ms.
32  void idle() {
33      static int lastTime = 0;                // time of last redraw
34      int time = glutGet(GLUT_ELAPSED_TIME);  // current time
   
35      if(lastTime == 0 || time >= lastTime + 40) {
36          lastTime = time;
37          glutPostRedisplay();
38      }
39  }
   
40  // When window becomes visible, we want the window to
41  // continuously repaint itself.
42  void visible(int vis) {
43      glutIdleFunc(vis == GLUT_VISIBLE ? idle : NULL);
44  }
   
45  int main(int argc, char **argv) {
46      glutInit(&argc, argv);
47      glutInitDisplayMode(GLUT_SINGLE | GLUT_RGB);
48      glutInitWindowPosition(50, 100);    // Set up display window.
49      glutInitWindowSize(450, 150);
50      glutCreateWindow("Moving Wagon");
   
51      init();
52      glutDisplayFunc(draw);
53      glutVisibilityFunc(visible);
54      glutMainLoop();
55      return 0;
56  }
   
57  // To compile: gcc moving_main.c wagon.c wheel.c -lglut -lGLU -lGL -lm