Reputation: 83
In my game I have objects that gets spawned regularly on a 0.45s basis. When spawned into the world, they'll get a copy of the nanoTime at that time. That way I can check with the current nanoTime to remove the object after a certain amount of time has passed.
Now the problem is when you pause the game. Because the nanoTime will, of course, keep going which will make the objects disappear directly after you get out of the pause screen (if the pause screen was up longer than the amount of time it takes to remove the object).
Is there a way to freeze the nanoTime or something like that when you enter the pause screen and resume from where it left when you exit so the objects won't disappear directly after you get out of the pause screen?
Upvotes: 1
Views: 265
Reputation: 936
I would recommend changing the way you store your spawned objects. Rather than storing the time when they are added to the world, you should store how long they have left to live.
On each render frame libGDX provides you with a delta
parameter to measure how long has elapsed since the last render time. You would decrement from the timeLeftToLive
variable (or some other name) this delta
value if the game is not paused.
The code below illustrates my point (just a dummy class):
class ObjectTimer {
private float timeToLive = 0; //How long left in seconds
public ObjectTimer(float timeToLive) {
this.timeToLive = timeToLive;
}
//This method would be called on every render
//if the game isn't currently paused
public void update() {
//Decrease time left by however much time it has lived for
this.timeToLive -= Gdx.graphics.getDeltaTime();
}
//Return if all the time has elapsed yet
//when true you can de-spawn the object
public boolean isFinished() {
return timeToLive <= 0;
}
}
Then you might have a loop in your main game that would do the updating something along the lines of:
//Do this if the game isn't paused
if (!paused) {
//For each of your sprites
for (MySprite sprite: spriteArray) {
//Update the time run for
sprite.getObjectTimer().update();
//Check if the sprite has used all its time
if (sprite.getObjectTimer().isFinished()) {
//Despawning code...
}
}
}
Upvotes: 3