Home > database >  How do I stop the timer from counting down when I switch to pause state?
How do I stop the timer from counting down when I switch to pause state?

Time:02-02

I have a java game wherein there is a countdown timer from 60 secs. It works fine, but when I pause the game and return back to play state. the original time is now reduced because I found out that the timer still keeps running from the system no matter what gameState I'm in. How do I fix this?

I tried storing the remainingTime to a pauseTime variable whenever I switch states, and just subtract it and stuff. But my efforts seem to failed.

// GET ELAPSED TIME
        if(gp.gameState == gp.playState && remainingTime >= 0) {
            soundCounter--;
            elapsedTime = System.currentTimeMillis() - startTime;
            remainingTime = totalTime - elapsedTime;
            if(remainingTime <= 0) {
                remainingMilliseconds = 0;
                remainingSeconds = 0;
                remainingMinutes = 0;
                // GAME OVER
                gp.gameOver();
            } else {
                remainingMilliseconds = remainingTime % 1000;
                remainingSeconds = (remainingTime / 1000) % 60;
                remainingMinutes = (remainingTime / 1000) / 60;
            }
        }
        // DRAW TIMER
        timeString = String.format("d:d:d", remainingMinutes, remainingSeconds, remainingMilliseconds);

CodePudding user response:

Your problem is that you are calculating your elapsed time forever since the first startTime.

One of the solution would be to calculate a delta (difference) time between loop iterations.

Here some very primitive code that should get you started:

public static void main(String[] args) {
    boolean paused = false;
    long lastRun = System.currentTimeMillis();
    long elapsed = 0;

    System.out.println("Game start");

    while (true) {
        long now = System.currentTimeMillis();
        long delta = now - lastRun;

        if (!paused && delta > 0) {
            elapsed  = delta;

            // Do game stuff
            System.out.println("Elapsed: "   elapsed);
            if (elapsed >= 5000) return;
            lastRun = now;
        }
    }
}
  • Related