Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java game slow update for a few seconds

I'm making a game of life clone, (you know, just for fun) and I'm having a little problem with the update (tick) method.

Here is the the update and render loop:

while (running) {
    double nsTick = 1000000000 / amountOfTicks;

    long now = System.nanoTime();
    deltaRender += (now - lastTime) / nsRender;
    deltaTick += (now - lastTime) / nsTick;
    lastTime = now;

    while (deltaRender >= 1){
        render();
        frames++;
        deltaRender--;

        if (tickRunning) {
            while(deltaTick >= 1) {
                tick();
                ticks++;
                deltaTick--;
            }
        }

        if (System.currentTimeMillis() - timer > 1000){
            timer += 1000;
            System.out.println("Ticks: " + ticks);
            frames = 0;
            ticks = 0;
        }
    }
}

stop();

As you can see I have separated the render and tick functions because tick's rate is controlled by the user in real time.

The problem is that, when the game starts, (or is unpaused), tick has an unstable update rate for a few seconds (around 10) and then adjust to the right one. Can that be fixed?

The game currently runs on a single thread.

like image 450
das Avatar asked Dec 05 '25 09:12

das


1 Answers

The problem appears to be that when you are pausing the game, you are still counting up the tick()s you have to execute (that is, deltaTick continues to increase); and these piled up tick()s are than executed at once when the game is resumed. There are multiple solutions here; one would be to pause increasing deltaTick, when the game is paused:

if (tickRunning) {
    deltaTick += (now - lastTime) / nsTick;
}

Another approach would be to simply set deltaTick to 0 when you resume or start the game.

like image 56
Lazzaro Avatar answered Dec 06 '25 22:12

Lazzaro



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!