Java-从播放时间中减去暂停时间



我有两个实例变量: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);

经过时间量的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;
}
}

}

最新更新