【发布时间】:2016-12-10 08:45:35
【问题描述】:
override func update(currentTime: NSTimeInterval) {
// ...
}
如何在更新方法中停止 currentTime? 我想计算游戏开始后的时间。 当玩家点击暂停按钮时,当前场景成功暂停。 但是,currentTime in update 正在移动。
【问题讨论】:
标签: ios swift sprite-kit
override func update(currentTime: NSTimeInterval) {
// ...
}
如何在更新方法中停止 currentTime? 我想计算游戏开始后的时间。 当玩家点击暂停按钮时,当前场景成功暂停。 但是,currentTime in update 正在移动。
【问题讨论】:
标签: ios swift sprite-kit
当场景暂停时,update不会被调用,试试这段代码:
class GameScene: SKScene {
override func didMove(to view: SKView) {
let wait = SKAction.wait(forDuration: 2)
let pause = SKAction.run { self.isPaused = true }
self.run(SKAction.sequence([wait, pause]))
}
override func update(_ currentTime: TimeInterval) {
print("update")
}
}
"update" 将仅打印前 2 秒。这证明暂停场景会停止update。您可能不是在暂停场景,而是在场景中运行所有动作的节点。
除此之外,通过暂停场景来实现暂停屏幕并不是一个好主意,因为如果场景暂停,用户无法通过点击离开暂停屏幕。此外,您不能在暂停屏幕中显示炫酷的动画。
我通常做的是有一个后台节点。每个游戏精灵都被添加为背景节点的子节点。在暂停屏幕中,背景暂停,但场景仍在运行。然后我将暂停屏幕精灵添加为场景的直接子节点,以便您仍然可以与暂停屏幕进行交互。
您实际上并不需要“停止”update 方法。您只需要在方法中检查游戏是否暂停即可。如果是,请立即返回。
如果你想测量玩家开始游戏后经过了多少时间,你也可以使用Date 对象。在游戏开始时创建一个Date,在用户暂停时创建另一个Date。调用timeIntervalSince 方法就可以了!
【讨论】:
我已经实现了如下的暂停,我认为代码是不言自明的,但我添加了一些 cmets:
// BaseScene inherits from SKScene but adds some methods, e.g. for dealing with
// controller input.
class GameScene : BaseScene {
// The previous update time is used to calculate the delta time.
// The delta time is used to update the Game state.
private var lastUpdateTime: NSTimeInterval = 0
override func update(currentTime: CFTimeInterval) {
// NOTE: After pausing the game, the last update time is reset to
// the current time. The next time the update loop is entered,
// a correct delta time can then be calculated using the current
// time and the last update time.
if lastUpdateTime <= 0 {
lastUpdateTime = currentTime
} else {
let deltaTime = currentTime - lastUpdateTime
lastUpdateTime = currentTime
Game.sharedInstance.update(deltaTime)
}
}
// A method on BaseScene that is called when the player presses pause
// on controller.
override func handlePausePress(forPlayer player: PlayerIndex) {
paused = true
lastUpdateTime = 0
}
}
My Game 单例仅在更新游戏状态时使用增量时间(自上次调用以来的时间差)。
【讨论】: