I hit a wall with this timer.
I tried to create this timer which when the game starts, it will start counting. When the character dies, it stops. I got it all working, but my problem is I can't get it restart for the next round.
Here is my code.
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
}
}
From Apple Doc
invalidate()
Stops the receiver from ever firing again and requests its removal from its run loop.
If you have to start timer again, You need to initialise timer again.You have to make a new one.Once invalidated, timer objects cannot be reused.