Table of Contents

[ Intro | Begin | if/else | Loops | Arrays | Graphics | Animation | Mouse | Game | Real | Methods | Class | Class 2 | Applet | MouseClick | Thread | Button ]


Java For Kids tutorial 7

Java Animation

In a for loop draw an object with moving x or y coordinates.

Use the delay(time) function to animate.

Use clearDrawing as well.

Here is an example. Imagine it is an alien coming toward you.

    void main() {
        setColor(red);
        for(int count = 0; count < 50; count++) {
                fillCircle(150, count*5, 50);
                delay(0.1);
                clearDrawing();
        }
    }

Try it without clearDrawing() by commenting out that line. e.g.

        // clearDrawing();

Notes on Above Java Code:

So you can see that y increases by 5 every time the loop goes round, until count = 49. Then y will equal 49 * 5 = 245.

Frames Per Second (fps) in Java Animations

Also change the delay time. delay stops the program executing for the time that it put between the brackets ( ) after the word delay. The time is give as a double and not an int. That allows us to use fractions of a second as a time delay.

If a time delay of 0.10 seconds is given, then the animation's frame rate is 10 frames per second. Video(PAL) goes at 25 frames per second. USA TV runs at 30 fps(frames per second). Japanese anime usually runs at about 4 or 5 frames per second.

The more frames per second an animation is given, the smoother the animation will look. So try the delay in the above animation at 0.5 seconds (delay(0.50);) and see what it looks like. Is it jerkier or smoother than delay(0.1)? Try delay(0.025).

Choose the animation fps to suit the speed of the computers processor and filesize.

Another way of doing it

getDrawingHeight() returns the height of the window as an int. We could make the ball move down the screen until the y co-ordinate reaches the window. But we have to subtract the height of the ball, dont we?

Nooo, maybe we want to let the ball go offscreen, so let's make the ball go downwards until y equals the height of the window. Lets do it!

    void main() {
        int y = 0;		// initialize y
        int howFar = getDrawingHeight();
 
        setColor(green);        // green ball
        while (y < howFar)
        {
            // draw circle
            fillCircle(150, y, 50);
 
            // add 5 pixels each time it loops
            y = y + 5;
            delay(0.1);
            clearDrawing();
        }
    }

(to be continued…)