0
\$\begingroup\$

I am working on a game that has a lot of time-passed checks of the following format. These work great, but there is a problem when the game is paused:

If paused for any meaningful amount of time, the if statement will become true.

const t = new Date().getTime(); // Get the current time (in ms)
const fireCooldown = 500; // The time to wait before firing again (in ms)

if(t > lastFireTime + fireCooldown) {
   lastFireTime = t;
   fire();
}

How can I integrate pause functionality into this - in a way where pausing does not make the if statement true?

\$\endgroup\$

1 Answer 1

1
\$\begingroup\$

The usual way to handle this it to separate the notion of "game time" from "real time".

While the game is running, you increase your game time variable's value each frame / simulation step.

Scripts that need a timestamp to work with will read the current value of that game time variable.

When your game is paused, you disable the code that increases the game time variable. Now for anything that's checking timestamps in game time, it's as though time has frozen — exactly what you want.

The challenge often comes in due to the fact that you don't want everything to pause. Animations in the UI like the pause menu should still play. So you need to set up your scripts to read either realtime or game time based on their context.

As a bonus, tracking game time this way also lets you enable slow motion and (some) fast forward effects, by just scaling how much you add to the game time variable you can alter the perceived flow of time for all scripts that use it.

\$\endgroup\$
2
  • \$\begingroup\$ Thank you, this helped clarify my thoughts! Essentially, I need to change const t = new Date().getTime(); to const t = gameTimeManager.getTime();. And then in gameTimeManager.update(), I need to add the time that has passed since the last frame to the current time - unless the game is paused, in which case I do not need to add time. \$\endgroup\$
    – Ben
    Sep 14, 2020 at 12:25
  • 1
    \$\begingroup\$ Yep! If your game can run for hours or longer, watch out for the loss of floating point precision you can get from adding small increments to a large total. \$\endgroup\$
    – DMGregory
    Sep 14, 2020 at 12:28

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .