Java – LibGDX stops the time counter when paused

LibGDX stops the time counter when paused… here is a solution to the problem.

LibGDX stops the time counter when paused

In LibGdx, is there a way to pause the delta time when the user temporarily pauses the screen/away from the application (e.g. an incoming call)? For example, when it takes 10 seconds for the user to read the message when the message is displayed, usually, I get the start time of the message display, do the calculation in render() to get the elapsed time (currentTime – MessageStartedTime), if it takes > 10 seconds, and then close the message and everything works, right. Imagine a scenario where the user is reading the message (let’s say it takes 2 seconds), the incoming call takes 20 seconds, and when the process returns to my application, it takes > 10 seconds, so the message will be deleted even though the message is only displayed for 2 seconds.

So, my

question is, is there a master timer that I can implement in my application for such purposes? What is the best way to achieve it?

Solution

I have two game states, which are:

GAME_RUNNING
GAME_PAUSED

I set the status to GAME_PAUSED when pause() is called, and GAME_RUNNING when resume() is called.

Then when I run update() on my game, I check this status and if it pauses, I set delta to 0.

float deltaTime = game.state == GAME_PAUSED ? 0 : Gdx.graphics.getDeltaTime();

This means that when all my gameobjects are updated, their changes are multiplied by 0 and nothing changes. We can also add a condition that is only updated when deltaTime > 0.

If you have a timer, you will update this timer somehow:

public void update(World world, float delta) {
    frameTimer += delta;

if( frameTimer >= rate / 1000) {
        fireAtEnemy(world);
        frameTimer = 0;
    }
}

Because the increment is now 0, the timer does not increase until the game returns to GAME_RUNNING after resume().

In addition, you can

add an extra state called GAME_RUNNING_FAST, and when this state is set, you can multiply deltaTime by 2. If you have all the updates related to deltaTime, your entire game will run at double speed. If that’s what you want.

Related Problems and Solutions