I’m developing a high speed scroller. It is extremely important that I have a high resolution timer. Since I’m restricting myself (perhaps needlessly?) to working in pure Java, this has narrowed my search to utilizing the newly supported System.nanoTime() method in Java 1.5b.
Here’s how I’m thinking of utilizing it. Perhaps you can tell me if I’m on the right track. In the main game thread/static void main we’ve got:
long startTime = System.nanoTime();
long endTime;
double difference;
int FPS = 50;
int sec = 0;
while(true)
{
endTime = System.nanoTime();
difference = ((double)(endTime - startTime));
if(difference >= ((double)(1000000000 / FPS)
{
startTime = endTime;
sec++;
//Frame!
}
if(sec == FPS)
{
sec = 0;
//Second!
}
}
Since Thread.sleep() is unreliable, this is the only method I can think of to keep a steady beat. The only problem with this code is the junk that goes on during and in between frames. Right now with just the code in this loop, it’s able to keep time. I imagine that once things get processor heavy, the code will desync from the system clock. If such is the case, the computations done each frame need to take 1/FPS*1billion nanoseconds or less to complete or the game will lag behind. Additionally, this timer is more prone to to lag when other programs are open. Even unreliable methods that rely on Thread.sleep(1) are stronger against such things due to the way Java handles the associated threading.
Any suggestions as to how I can safegard this? Perhaps I am underestimating Java and should assume it has the capability to compute heavy things within my time constraints? (I doubt it. As it is now, I have to “preload” all my graphics long before I expect to use them or the game will lag.)
Any other approaches to this would be greatly appreciated. Keep in mind that I wish to keep things purly in Java. I’m very much the type of person who wants to “reinvent the wheel” and if I get over my head dealing with dlls and other languages, I’ll spend too much time trying to learn the finer details of such things rather than on the game.
Edit: It seems that I might be able to make this a bit more robust if I could throw it in a thread and use yield(). Could someone explain to me exactly how yield() works? The API is a bit misleading. If it waits for other threads, does this mean that it waits for any one of them to synchronize? Or does it merely perform the same thing that sleep() does only without a specified duration? If the latter, how might I utilize yield() to make a thread pause for a certain amount of time (i.e: the length of a frame)?