Can't get consistent FPS in Applet

Hi everyone,

I have a problem thats really starting to do my head in! :’(
I have a online game that is run via an applet in a browser. It works OK, except that I can’t get consistent timing for the FPS. It has balls which move about, but sometimes they speed up/slow down non- linear manner. When I run the same game throught AppletViewer is nice and smooth. Its only when I run in an applet I have the issues. However I’m stuck using and applet as it needs to be easy and quick to use for the online users.

The code for the thread is :

long framerate = 1000 / 30; // frames per sec
long oldtime;
while (true) {
oldtime = System.currentTimeMillis();

  // update object movement                        
  // draw stuff
  
  long currenttime = System.currentTimeMillis();
  if (currenttime - oldtime < framerate) {
  try {
        Thread.sleep((oldtime + framerate) - currenttime);
  } catch (InterruptedException e) {
  }

}

Edited so say: I’m using a doubled BufferedImage to do the drawing. I’m not sure if its an issue with the consistency of the FPS or whether its the timing between calculating the movement of the objects. I’m not calling pain directly rather update() FYI.t

Don’t lock the framerate. That might be causing the problem. Do all calculations based on time.

But is is based on time no?
what do you mean? (sorry bit slow today)

You are locking you framerate to 30 FPS. So all your updates occur each frame.

If you use time based movement, you just start your loop, check how much time has elasped since the last update and update all game objects based on time. This will give you more consistent results.

ie, if you have a game object that moves 50 pixels per second and it has been 20 milliseconds since the last update then you move it 1 pixel. If the next update is 40 milliseconds, the 2 pixels.

20 milliseconds = 0.02 seconds.
50 pixels per seconds * 0.02 seconds = 1 pixel

It is also advisable to have all variables that are affected by time be floating point.

This is the framelimiter i came up with, don’t know if its any good, but it seems to work. =)

        //framelimiter-------------------------
        while(System.currentTimeMillis() < nextTick){
            try {Thread.sleep(1);}
            catch (InterruptedException e) {}
        }
        nextTick = System.currentTimeMillis() + 30;
        //-------------------------------------

Thread.sleep(1) is not a good idea. It has been mentioned on many threads in these forums that the granularity of the timer for Java in Windows is 10ms, which means that your thread will not reliably sleep for any time period less than 10ms. I have also read that sleeping for less than 10ms on a Windows machine can cause the system’s clock to drift, which is not cool. All this is assuming you plan on running your software in Windows. If you don’t, ignore everything I just said :].

No, i am running it under windows. thanks for the heads up =)