Hi
A fixed framerate would be
int fps = 30; //whatever you want
int timeperframe = 1000/fps;
while(running)
{
long start = System.nanoTime();
Do decisions for this frame, AI
Update all Objects / Move
Check Collisions and stuff
Paint the frame
long end = System.nanoTime();
long duration = (end - start) / 1000000;
long sleeptime = Math.max( timeperframe-duration, 5);
try
{
Thread.sleep(sleeptime);
} catch(Exception e)
{
}
}
This would be a fixed framerate. After each frame it sleeps just as long so that the frames all take
the same time. You must specify your framerate. It should take a minimum sleep time of at least a few ms so that your game loop doesnt starve out other java threads.
When the pc is not fast enough to do the frames in the target time, the game will slow down.
to conquer this, you can make a dynamic framerate with
long timesincelastframe = lastframestart - thisframestart;
and do all updating based on this time. If more time passed, things will move a greater distance.
be sure to make a good collision detection, because fast things might jump quite some distance if the fps is low,
and they might just overjump each other while they should have collided.
If you have very expensive tasks, either make another thread, let them run there and use the results when its done, or
divide it into small packages and do one package per frame until all are done.
pathfinding for example might be restricted to search 100 tiles per frame. you wont notice when it takes 3 or 4 frames to make
a path.
-JAW