Search code examples
javagame-loop

Physics update lag


I ran into a problem, where doing everything on a single thread may lead to some lags. The problem is, when I start to create loads of new objects (like 300 per second), my physics rate drops.

I sort all rendering objects each frame, so I would know which one to draw in which order, this might be the reason why it can handle only so little, but even if that was removed, there still would be like max operations per update, otherwise physics will lag.

Any ideas on how to achieve the correct zOrder, or remove possible physics lags?

Or detach physics from rendering ... ?

My game loop:

while (isRunning) {

    currentFrameTime = System.nanoTime();
    passedTime = currentFrameTime - lastFrameTime;
    lastFrameTime = currentFrameTime;

    physicsPassedTime += passedTime;
    updatePassedTime += passedTime;

    if (physicsPassedTime >= (double) 1_000_000_000 / physicsRate) {

        physicsPassedTime = 0;

        PhysicsUpdate();
    }

    if (updatePassedTime >= (double) 1_000_000_000 / refreshRate) {

        updatePassedTime = 0;

        Update();
        Render();
        LateUpdate();
    }
}

Solution

  • Looks like the best solution (as suggested in comments) will be to run a second loop on a second thread with just physics update, and everything else on the other thread.

    That way frame drops should not intervene with the physic updates.

    Edit: Implemented this, and works like charm. I'll mark the answer when I'll be able to.