我在Swift中创建了一个游戏,其中涉及怪物的出现。怪物会根据计时器的出现和消失,如下所示:
func RunAfterDelay(_ delay: TimeInterval, block: @escaping ()->())
{
let time = DispatchTime.now() + Double(Int64(delay * Double(NSEC_PER_SEC))) / Double(NSEC_PER_SEC)
DispatchQueue.main.asyncAfter(deadline: time, execute: block)
}
///Spawn Monster
RunAfterDelay(2) {
[unowned self] in
self.spawnMonster()
}
DispatchQueue.main.asyncAfter(deadline: time, execute: block)
我已经解决了这个问题,并希望在下面的结论中分享我的时间研究/编码。为了更简单地陈述问题,我实际上想实现这一目标(不仅仅是简单地使用SpriteKit场景暂停,这很容易):
//Take the delay you need (delay variable) and add this to the current time
let calendar = Calendar.current
let YOUR_INITIAL_TIME_CAPTURED = calendar.date(byAdding: .nanosecond, value: Int(Int64(delay * Double(NSEC_PER_SEC))), to: Date())!
//Calculate the remaining delay when you start your timer back
let elapsedTime = YOUR_INITIAL_TIME_CAPTURED.timeIntervalSince(Date)
let remainingDelay = YOUR_INITIAL_TIMER_DELAY - elapsedTime
let timerKey = UUID().uuidString
let myTimer: Timer = Timer.scheduledTimer(withTimeInterval: delay, repeats: false) {
_ in
block()
self.timers.removeValue(forKey: timerKey)
}
}
addTimer(delay: 4, repeating: true)
{ [unowned self] in
self.spawnMonster()
}
关于ios - 在Swift中“暂停”游戏,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41054306/
欢迎光临 OStack程序员社区-中国程序员成长平台 (https://ostack.cn/) | Powered by Discuz! X3.4 |