我用这个计时器打了一堵墙。
我试图创建这个计时器,当游戏开始时,它将开始计数。当角色死亡时,它会停止。我把它全部工作了,但我的问题是我不能让它重新开始下一轮。
这是我的代码。
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
}
}
答案 0 :(得分:2)
invalidate()
阻止接收器再次发射并请求将其从运行循环中移除。
如果必须再次启动计时器,则需要再次初始化计时器。您必须重新启动计时器。一旦失效,计时器对象将无法重复使用。