Here are two game loops… one is of my creation, the other is the game loop from Minicraft
I can’t figure out why my update’s “stutter” and his are super smooth…
Here’s mine:
public static final long nano_milli = 1000000L;
public static final long nano_sec = 1000000000L;
public static final long milli_per_sec = 1000L;
public static final long ups = 32;
long update_frame = 0;
long update_frame_length = (milli_per_sec / ups) * nano_milli;
private void gameLoop2() {
while (running) {
now = System.nanoTime();
while (update_frame + update_frame_length <= now) {
update();
update_frame += update_frame_length;
}
render();
try{ Thread.sleep(2); } catch(Exception e) {}
}
}
Here’s his:
private void gameLoop() {
long lastTime = System.nanoTime();
double unprocessed = 0;
double nsPerTick = 1000000000.0 / 60;
while (running) {
long now = System.nanoTime();
unprocessed += (now - lastTime) / nsPerTick;
lastTime = now;
boolean shouldRender = true;
while (unprocessed >= 1) {
update();
unprocessed -= 1;
shouldRender = true;
}
try { Thread.sleep(2); } catch (InterruptedException e) { e.printStackTrace(); }
if (shouldRender) {
render();
}
}
}