A simple animation: ball.c

The module ball.c shows a circle bouncing to the edge of the screen.

We use two variables x, y for storing the current position of the ball, and two other variables dx, dy for the direction. At each step, we delete the ball from its current position, change the coordinates (x += dx; y += dy), and draw the circle in the new position.

In other words, we define the four variables we need at the beginning of the program:

  int x=10, y=10;     /* position of the ball */
  int dx=1, dy=1;     /* direction of the ball */
At each time step, we have to remove the ball from its current position:
  /* draw something */
  while (1)
      /* remove the ball from the screen */
      XClearArea(dpy, root, x, y, 40, 40, False);
We can now change the position of the ball, and redraw it in the new position.
      /* change position */

      /* draw in the new position */
      XFillArc(dpy, root, g, x, y, 40, 40, 0, 360*64);
Each time the ball reaches the border of the screen, it must bounce back. This is done by checking whether x is either 0 or wa.width-40. If this is the case, we change the sign of the direction.
      /* bounce (if the ball is at the edge of the screen) */
      if( x<=0 || x>=wa.width-40 )
        dx= -dx;
      if( y<=0 || y>=wa.height-40 )
        dy= -dy;
Note that the ball flickers. This can be avoided using the double buffering tecnique.