Animation and Keyboard

Moving in All Four Directions

Expanding the previous program so that the ball moves in all four directions seems simple enough. Let us provide the source code:

    int previousTime = tickCount;
    double x = SCREEN_W/2;
    double y = SCREEN_H/2;
    double vx = 0;
    double vy = 0;
    while (!key[KEY_ESC]) {
        int elapsedTimeInTicks = tickCount - previousTime;
        previousTime += elapsedTimeInTicks;
        if (key[KEY_LEFT])
            vx -= elapsedTimeInTicks;
        if (key[KEY_RIGHT])
            vx += elapsedTimeInTicks;
        if (key[KEY_UP])
            vy -= elapsedTimeInTicks;
        if (key[KEY_DOWN])
            vy += elapsedTimeInTicks;
        x += vx*elapsedTimeInTicks/1000;
        y += vy*elapsedTimeInTicks/1000;
        clear_to_color(surface, makecol(255,255,255));
        circlefill(surface, int(x), int(y), 50, makecol(0,0,255));
        blit(surface, screen, 0,0, 0,0, SCREEN_W,SCREEN_H);
        rest(20);
        }
    return 0;

This will enable you to move the ball anywhere across the screen by using all four cursor keys.

To enable this functionality, the program has to process the y-coordinate in the same manner it processes the x-coordinate. Accordingly, there are now two variables for position, named x and y, and two variables for velocity, named vx and vy. There have to be two statements for applying the motion, one for each coordinate. Finally, the circle has to be drawn at coordinates given by variables x and y.

Needless to say, this all is the consequence of our drawing surfaces being two-dimensional, like a piece of paper is. To work in three dimensions, we would have to add the code for the third coordinate usually named z. Unfortunately, the Allegro library does not have the functionality to draw three-dimensional objects, as such functionality usually entails many other complications.