How should we make fixed timestep in Java? I think there are 2 ways:
- Synchronised game loop using
while
. - Asynchronised game loop using
Thread
.
The most important thing is performance and accuracy. So what's the best way?
This is synchronised game loop:
double timeStep = world.getSettings().getStepFrequency();
long lastTime = System.nanoTime();
while (true) {
long currentTime = System.nanoTime();
double elapsedTime = (currentTime - lastTime) / 1000000000.0;
if (elapsedTime >= timeStep) {
lastTime = currentTime;
world.update(elapsedTime);
}
}
This is asynchronised game loop:
double timeStep = world.getSettings().getStepFrequency();
long lastTime = System.nanoTime();
Thread loop = new Thread() {
public void run() {
while (true) {
long currentTime = System.nanoTime();
double elapsedTime = (currentTime - lastTime) / 1000000000.0;
lastTime = currentTime;
world.update(elapsedTime);
try {
Thread.sleep((long) Math.floor(timeStep * 1000));
} catch (InterruptedException e) {}
}
}
};
loop.start();
The synchronised game loop uses lots of CPU (I think 1 core? that's ~25% for me).
CPU usage of the asynchronised game loop is almost 0%.
Note: The game I want to do is WebSocket
based game. The server is for physics, and HTML5's canvas is for rendering.
What way do you prefer? Why? Is there any better way?