|
double-buffered Java animation
[click the applet to re-init the ball]
This Java applet demonstrates the following:
Double buffering. That is, composing the image off-screen
and then drawing that final image to the screen. This technique avoids
annoying flicker that results from drawing and erasing everything on-screen.
Scaling by time. Rather than moving the ball a fixed number of
pixels per frame, the ball's position and velocity are stored as floating
point values. Motion is calculated by moving the ball a distance scaled by
the amount of time elapsed since the previous frame. This technique
provides the user with what appears to be the exact same motion speed from
one computer to the next, regardless of the framerate that their PC/browser
is capable of. It also allows the applet to run as fast as possible, so
faster computers will display smoother animation, rather than a
faster-moving ball.
Timer averaging. Java's timer is notoriously erratic. In general I
have found that calling System.currentTimeMillis() is accurate to roughly
50ms intervals. What that means is that if you call the function more than
once within a 50ms time interval, you will not get a properly updated time.
Since 50ms is good for only 20 frames per second, and since the applet will
generally run at faster rates than that on fast computers, scaling by time
becomes choppy and inaccurate. What this applet does is records the time
intervals for the last 8 frames in order to estimate a far more
accurate elapsed-time for each frame.
Threading techniques. If you come from a C, BASIC, or ASM background,
Java's intrinsic multithreading may seem a little wierd. This applet should
explain how to get a stable main loop up and running, and hopefully help you
to avoid the pitfalls associated with fragile Java implementations prevalent
in most web browsers.
tutorial © 1999-2000 - Mike Linkovich
last updated: Dec 26 2000
|