You need to do two things:
Firstly, regulate the sleep time by however long the CPU has taken for its processing. So for a really slow CPU, the sleep will be ‘0’. For a fast machine, it could be up to 40ish. You would also see this as the applet using less CPU time - 90%+ on a slow machine, and 20%+ on a fast machine.
e.g: To stick to 20 fps:
lastTime = currentTime;
currentTime = System.currentTimeMillis();
long pause = 50 - (currentTime - lastTime);
if(pause < 0) pause = 0;
Thread.Sleep(pause);
currentTime = System.currentTimeMillis();
Secondly, you have to perform the logic updates when neccesary, i.e. when enough time has passed:
// Define this somewhere else...
static long elapsedTime;
...
elapsedTime += currentTime - lastTime;
while(elapsedTime > 50)
{
// Do 50ms worth of updating
elapsedTime -= 50;
}
These examples are for 20 frames per second update (20 fps = 50ms per frame, hence the '50’s in the examples). Due to Windows 98 (& Windows Millenium) timers only having 50ms resolution, this is the best you can do on these systems. Windows 2000, XP, Macs or Linux have better timer resolutions so you can aim for higher framerates. Just adjust the ms times: for 30fps, use ‘33’, for 50fps use ‘20’, etc.
Hope this helps,