Hello,
For over two years I’ve been using this game loop, but now, I need delta and I just found out that this game loop delta isn’t that great.
I would like to ask you guys how to create a decent game loop with, updates happening 60 times or maybe 30 times per second and ticks once per second with delta.
Here is what I’ve been using.
public void run() {
// Calling the initialize Method to setup our environment
init();
// Variables for the FPS counter
long lastTime = System.nanoTime();
double ns = 1000000000.0 / 60.0;
long lastTimer = System.currentTimeMillis();
int frames = 0;
int updates = 0;
int checking = 0;
int sum = 0;
int avg = 0;
double delta = 0;
while (running) {
long now = System.nanoTime();
delta += (now - lastTime) / ns;
lastTime = now;
if (delta >= 1) {
// 60 times per second this is reached
update(this.public_delta);
updates++;
delta--;
}
// Render as many times as u can
render();
frames++;
Display.update();
if (System.currentTimeMillis() - lastTimer > 1000) {
lastTimer += 1000;
// Once per second this is reached
this.public_delta = delta;
this.public_fps = frames;
String title = GeneralSettings.fullname + " FPS: " + frames + " UPS: " + updates/* + " Delta: " + this.getDelta() */;
if (GeneralSettings.useAverageFPS) title += " Average: " + avg;
if (GeneralSettings.showLightFloat) {
if (world != null) title += " Light: " + world.DAY_LIGHT;
}
Display.setTitle(title);
if (GeneralSettings.useAverageFPS) {
sum += frames;
checking++;
if (checking == GeneralSettings.ticksPerAverage) {
avg = (sum / checking);
checking = 0;
sum = 0;
}
}
tick();
updates = 0;
frames = 0;
}
if (Display.isCloseRequested()) running = false;
Display.sync(fps_lock);
}
// If the game is closed, cleanup!
cleanup();
}
The problem with my game loop is, if I lock the fps at 30 for example, the UPS will also be lock at 30.
Also my Delta sometimes is like 0.03 others like 500.0. It reaches very high numbers when the computer cannot reach the 60 UPS per second.
How could I fix this?
Thanks
Joaogl.