我正在尝试使用SpriteKit为游戏创建一个倒数计时器,但每当我尝试运行countDown()时,我的游戏就会冻结。我很确定我的逻辑在这里是正确的。我不知道发生了什么。
func countDown(){
let countDownWait = SKAction.wait(forDuration: 1.0)
repeat {
self.run(countDownWait){
self.countDownTime -= 1
}
} while (self.countDownTime > 0)
if self.countDownTime == 0{
self.runGameOver()
}
}
答案 0 :(得分:1)
您可以在更新功能中检查一段时间,或者使用SKAction跟踪您在代码中执行的操作时间
let someLabel = SKLabelNode()
func countdown() {
var offset: Double = 0
for x in (0...10).reversed() {
run(SKAction.wait(forDuration: offset)) {
someLabel.text = "\(x)"
if x == 0 {
//do something when counter hits 0
//self.runGameOver()
}
else {
//maybe play some sound tick file here
}
}
offset += 1.0
}
}
答案 1 :(得分:0)
以下是我为Swift / SpriteKit' Breakout'解决这个问题的方法。应用。我希望在主游戏屏幕上从5比1倒数,但在球开始移动之前。我添加了这些功能,然后在didMoveToView
结束时调用倒计时(5):注意ball.physicsBody!.applyImpulse(CGVectorMake(20, 20))
是endCountdown
的最后一步,它启动球并有效地开始游戏。
func countdown(count: Int) {
countdownLabel.horizontalAlignmentMode = .Center
countdownLabel.verticalAlignmentMode = .Baseline
countdownLabel.position = CGPoint(x: size.width/2, y: size.height*(1/3))
countdownLabel.fontColor = SKColor.whiteColor()
countdownLabel.fontSize = size.height / 30
countdownLabel.zPosition = 100
countdownLabel.text = "Launching ball in \(count)..."
addChild(countdownLabel)
let counterDecrement = SKAction.sequence([SKAction.waitForDuration(1.0),
SKAction.runBlock(countdownAction)])
runAction(SKAction.sequence([SKAction.repeatAction(counterDecrement, count: 5),
SKAction.runBlock(endCountdown)]))
}
func countdownAction() {
count--
countdownLabel.text = "Launching ball in \(count)..."
}
func endCountdown() {
countdownLabel.removeFromParent()
ball.physicsBody!.applyImpulse(CGVectorMake(20, 20))
}
答案 2 :(得分:-1)
尝试使用此解决方案来运行倒计时...
var seconds = 7200
var timer = Timer()
override func viewDidLoad() {
super.viewDidLoad()
runTimer()
}
func runTimer() {
timer = Timer.scheduledTimer(timeInterval: 1, target: self, selector: (#selector(self.updateTimer)), userInfo: nil, repeats: true)
}
@objc func updateTimer() {
if seconds < 1 {
timer.invalidate()
//Send alert to indicate time's up.
} else {
seconds -= 1
timerLabel.text = timeString(time: TimeInterval(seconds))
}
}
func timeString(time:TimeInterval) -> String {
let hours = Int(time) / 3600
let minutes = Int(time) / 60 % 60
let seconds = Int(time) % 60
return String(format:"%02i:%02i:%02i", hours, minutes, seconds)
}
答案 3 :(得分:-2)
你考虑过使用计时器吗? Here is a good tutorial。它可能需要20分钟才能完成它,但它会详细介绍启动,停止,暂停以及更多计时器。