0
我用這個定時器打了一堵牆。斯威夫特定時器停止後不重新啓動
我試圖創建這個計時器,當遊戲開始時,它將開始計數。當角色死亡時,它停止。我得到了所有的工作,但我的問題是我無法在下一輪重新啓動它。
這是我的代碼。
var startTime = NSTimeInterval()
var timer:NSTimer = NSTimer()
override func didMoveToView(view: SKView) {
let aSelector : Selector = "updateTime"
timer = NSTimer.scheduledTimerWithTimeInterval(0.01, target: self, selector: aSelector, userInfo: nil, repeats: true)
startTime = NSDate.timeIntervalSinceReferenceDate()
scoreLabel.fontName = "Helvetica"
scoreLabel.fontSize = 40
scoreLabel.text = "0"
scoreLabel.position = CGPointMake(CGRectGetMidX(self.frame), CGRectGetMaxY(self.frame) - 90)
scoreLabel.zPosition = 20
self.addChild(scoreLabel)
}
func updateTime() {
var currentTime = NSDate.timeIntervalSinceReferenceDate()
var elapsedTime: NSTimeInterval = currentTime - startTime
let minutes = UInt8(elapsedTime/60.0)
elapsedTime -= (NSTimeInterval(minutes) * 60)
let seconds = UInt8(elapsedTime)
elapsedTime -= NSTimeInterval(seconds)
let fraction = UInt8(elapsedTime * 100)
let strMinutes = minutes > 9 ? String(minutes): "0" + String(minutes)
let strSeconds = seconds > 9 ? String(minutes): "0" + String(seconds)
let strFraction = fraction > 9 ? String(fraction): "0" + String(fraction)
scoreLabel.text = "\(strMinutes):\(strSeconds):\(strFraction)"
}
func didBeginContact(contact: SKPhysicsContact) {
if (gameOver) == 0 {
timer.invalidate()
gameOver = 1
movingObjects.speed = 0
gameOverLabel.fontName = "Helvetica"
gameOverLabel.fontSize = 40
gameOverLabel.text = "Game over! press to restart."
gameOverLabel.position = CGPointMake(CGRectGetMidX(self.frame), CGRectGetMidY(self.frame))
gameOverLabel.zPosition = 20
labelHolder.addChild(gameOverLabel)
}
}
override func touchesBegan(touches: Set<NSObject>, withEvent event: UIEvent) {
if (gameOver == 0) {
my methods......
} else {
scoreLabel.text = "00:00:00"
gameOver = 0
}
}