LibGDX game logic and rendering sync in loop

I’ve just started LibGDX (read most of the wiki) and I’ve noticed in some examples there is a game logic update method call inside the game render loop, which effectively is the game main loop. Doesn’t this mean that the logic updating will only be done at the same rate as the graphic rendering loop? So then if the logic update method takes 500ms (extreme case), then i will get max 2fps??

*I understand that there is a delta time parameter to keep the logic simulation speed independent of hardware.

keep a fixed timestep
float TIME_STEP = 1/30f;//30 times a second
void render() {
accumulator += Gdx.graphics.getDeltaTime();
if (accumulator >= TIME_STEP) {
accumulator -= TIME_STEP;
screen.update(TIME_STEP);
}
screen.render();
}

@SuperMario

Change that [icode]if[/icode] into a [icode]while[/icode] loop, and it should play catch up when it couldn’t meet the target frame rate. You can also add in a max frameskip control there.


final float TIME_STEP      = 1 / 30f; // 30 times a second
final int   MAX_FRAMESKIPS = 5;       // Make 5 updates mostly without a render

float accumulator;
int   skippedFrames;

void render()
{
    accumulator += Gdx.graphics.getDeltaTime();

    skippedFrames = 0;

    while (accumulator >= TIME_STEP && skippedFrames <= MAX_FRAMESKIPS)
    {
        accumulator -= TIME_STEP;
        screen.update(TIME_STEP);

        skippedFrames++;
    }

    screen.render();
}

This should be more better, as playing catchup is often required on systems with low configuration.

I’ve overlooked that. I’m using it my current game so big thanks :wink:

A problem with that code is that you’re effectively limiting your frame rate to the update rate with that code. Although you will render as fast as you can (possibly >1000 FPS), you’ll be rendering the exact same frame multiple times until the next update, which is kinda pointless. A solution is to have a “high enough” update rate, but this can be very inconvenient for performance. Another is to add interpolation, so that you can generate additional frames inbetween the current and previous game state. This is the best alternative, but also the most complex to implement.