在libgdx中暂停TimeUtils

时间:2016-04-24 20:23:39

标签: java timer libgdx

在我的游戏中,我有定期以0.45秒为基础产生的物体。当产生这个世界时,他们会在那时获得nanoTime的副本。这样我可以检查当前的nanoTime,在经过一段时间后删除对象。

现在问题是当你暂停游戏时。因为nanoTime当然会继续运行,这会使你的对象在你离开暂停屏幕后直接消失(如果暂停屏幕的时间超过了移除对象所需的时间)。

有没有办法在你进入暂停屏幕时冻结nanoTime或类似的东西,并在你退出时从它离开的地方继续,这样你的对象在你离开暂停屏幕后不会直接消失? / p>

1 个答案:

答案 0 :(得分:3)

我建议您更改存储衍生对象的方式。您应该存储他们离开的时间,而不是存储它们被添加到世界的时间。

在每个渲染帧上,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...
        }
    }
}