Hi there,
There are times when I need to use a second timer. I’m always using the game loop for this, which is probably unclean and safe. What is the easiest way to create a second timer loop?
Thanks!
Hi there,
There are times when I need to use a second timer. I’m always using the game loop for this, which is probably unclean and safe. What is the easiest way to create a second timer loop?
Thanks!
The best solution depends on your needs, and implementation but generally speaking you should be able to ‘run’ a second timer on your game loop thread.
All you have to do is check the time (I’m talking about a unix timestamp format here) every frame, and if the time is more or equal than the time you want to monitor then trigger the event.
If you’re using Java2D watch out for Java’s poor [icode]System.currentTimeMillis();[/icode] implementation, as it will give you slightly incorrect results. You should be using [icode]System.nanoTime();[/icode] instead and then if you want to convert that to millis all you have to do is divide the result by 1000000.
However, if you’re using LWJGL you can use it’s bult-in [icode]Sys.getTime();[/icode] and then divide that by [icode]Sys.getTimerResolution();[/icode] and multiply by 1000, as this will provide you top notch time accuracy.
Here’s a pure Java sample for what you need:
private static final long washAt = getTime()+10000L;
public void gameLoop(){
long time = getTime();
if(time >= washAt){
washTheDishes();
}
}
public void washTheDishes(){
// ...
}
public static long getTime(){
return System.nanoTime()/1000000;
}
In this program you will have to do the dishes in 10 seconds (or 10000 millis) after the program starts. I suppose that the [icode]gameLoop()[/icode] method is getting called every frame. Now in that method we ask the computer for the current time, and if it’s greater or equal to [icode]washAt[/icode] then [icode]washTheDishes()[/icode].
Hope it’s all clear now.