在我的游戏中,我有以 0.45 秒为基础定期生成的对象。当生成到世界上时,他们会在那个时候得到一个 nanoTime 的副本。这样我就可以检查当前的 nanoTime,以便在经过一定时间后删除对象。
现在的问题是当您暂停游戏时。因为 nanoTime 当然会继续运行,这将使对象在您离开暂停屏幕后立即消失(如果暂停屏幕的时间长于移除对象所需的时间)。
有没有办法在你进入暂停屏幕时卡住 nanoTime 或类似的东西,并在你退出时从它离开的地方恢复,这样对象就不会在你离开暂停屏幕后直接消失?
最佳答案
我会建议改变存储衍生对象的方式。与其存储它们被添加到世界的时间,不如存储它们还剩多久。
在每个渲染帧上,libGDX 为您提供了一个 delta
参数来衡量自上次渲染时间以来经过了多长时间。如果游戏没有暂停,您可以从 timeLeftToLive
变量(或其他名称)中递减此 delta
值。
下面的代码说明了我的观点(只是一个虚拟类):
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;
}
}
那么您的主游戏中可能会有一个循环,它会按照以下方式进行更新:
//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...
}
}
}
关于java - 在 libgdx 中暂停 TimeUtils,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36828510/