【问题标题】:Java - subtract paused time from playtimeJava - 从播放时间中减去暂停时间
【发布时间】:2021-09-10 15:09:13
【问题描述】:

我有两个实例变量: private Instant elapsedTime;private Instant pauseTime;

然后我有一个方法可以根据经过时间和暂停时间计算播放时间,但它没有正确执行。 我当前的代码是:

public void pausePlay(boolean paused) {
        // If elapsed time isn't already made, make it
        if (elapsedTime == null) {
            elapsedTime = Instant.now();
        }
        if (paused) {
            pauseTime = Instant.now();
        } else {
            if (pauseTime != null) {
                elapsedTime = elapsedTime.plusMillis(Duration.between(elapsedTime, pauseTime).toMillis());
        }
    }
}

我第一次暂停程序时,它工作得很好。但是下一次暂停的问题是播放时间不是从程序暂停之前的位置开始计算的,而是回到程序第一次暂停之前的位置。

我已经尝试在方法中的任何位置将 pauseTime 设置为 null,但没有成功。

有什么解决办法吗?

=================================

编辑:我通过更改以下代码来修复它...

elapsedTime = elapsedTime.plusMillis(Duration.between(elapsedTime, pauseTime).toMillis());

...进入这个:

long pausedTime = Duration.between(pauseTime, Instant.now()).toMillis();
elapsedTime = elapsedTime.plusMillis(pausedTime);

【问题讨论】:

  • 播放时间与 elapsedTime 相同。当游戏暂停时,即在 elapsedTime 仍在运行的情况下激活 pauseTime,当它取消暂停时,需要从 elapsedTime 中减去 pauseTime。
  • 你的逻辑让我无法理解。你的目标到底是什么?您是否要在每种模式下累积经过的时间,暂停时经过多少时间以及在播放模式下经过多少时间?投票结束,因为不清楚。
  • 理解这个有多难?我试图从经过的时间中减去暂停的时间,所以游戏不会计算暂停时间。

标签: java time


【解决方案1】:

经过时间的 Duration 类

这对我来说不是很清楚,但我似乎理解您想要跟踪经过的时间以及其中有多少已暂停时间。我认为这比你的代码多一点,但还不错。下面的课程将播放时间和暂停时间视为非常对称的,并分别跟踪它们。也许您可以根据自己的需要进行调整。

使用Duration 类一段时间,例如在暂停和非暂停模式下花费了多少时间。

public class Game {

    // At most one of playTime and pauseTime is non-null
    // and signifies the game is either playing or paused since that instant.
    Instant playTime = null;
    Instant pauseTime = null;
    
    /** Not including pause time */
    Duration totalPlayTime = Duration.ZERO;
    Duration totalPauseTime = Duration.ZERO;

    /**
     * Records elapsed time.
     * Sets state to either paused or playing controlled by the argument.
     */
    public void pausePlay(boolean paused) {
        Instant now = Instant.now();
        
        // Add elapsed time since last call to either play time or pause time
        if (playTime != null) {
            totalPlayTime = totalPlayTime.plus(Duration.between(playTime, now));
        } else if (pauseTime != null) {
            totalPauseTime = totalPauseTime.plus(Duration.between(pauseTime, now));
        }
        
        if (paused) {
            playTime = null;
            pauseTime = now;
        } else {
            playTime = now;
            pauseTime = null;
        }
    }
    
}

【讨论】:

  • 感谢您的建议!我先尝试了一下,但后来我意识到我从一开始就做了错误的计算,现在它已经用更少的代码修复了。
猜你喜欢
  • 1970-01-01
  • 2014-08-13
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-05-04
  • 2016-07-31
  • 1970-01-01
相关资源
最近更新 更多