I want to display a score at near the top of the scene. Scoring is dependent on the amount of seconds you have lasted and whenever I have tried to implement using NSTimer, the number remains at 0. Thanks in advance!
我想在场景顶部附近显示一个分数。评分取决于您持续的秒数,每当我尝试使用NSTimer实施时,数字保持为0.提前感谢!
2 个解决方案
#1
You don't really need an NSTimer
. Since you are using SpriteKit, you can use SKAction
for this. Here's an example:
你真的不需要NSTimer。由于您使用的是SpriteKit,因此您可以使用SKAction。这是一个例子:
let increaseScoreAction = SKAction.runBlock { score++ }
let waitAction = SKAction.waitForDuration(1)
let groupAction = SKAction.group([increaseScoreAction, waitAction])
let repeatAction = SKAction.repeatActionForever(groupAction)
runAction(repeatAction)
#2
So, very simplistically this is what I tried and it works fine. I am storing the timer as an instance variable to invalidate it later if necessary.
所以,非常简单,这是我尝试过的,它工作正常。我将计时器存储为实例变量,以便稍后在必要时使其无效。
class ViewController: UIViewController {
var score: Int = 0
var timer: NSTimer?
override func viewDidLoad() {
super.viewDidLoad()
timer = NSTimer.scheduledTimerWithTimeInterval(1.0, target: self, selector: Selector("incrementTimer"), userInfo: nil, repeats: true)
}
func incrementTimer() {
score++
println(score)
}
}
#1
You don't really need an NSTimer
. Since you are using SpriteKit, you can use SKAction
for this. Here's an example:
你真的不需要NSTimer。由于您使用的是SpriteKit,因此您可以使用SKAction。这是一个例子:
let increaseScoreAction = SKAction.runBlock { score++ }
let waitAction = SKAction.waitForDuration(1)
let groupAction = SKAction.group([increaseScoreAction, waitAction])
let repeatAction = SKAction.repeatActionForever(groupAction)
runAction(repeatAction)
#2
So, very simplistically this is what I tried and it works fine. I am storing the timer as an instance variable to invalidate it later if necessary.
所以,非常简单,这是我尝试过的,它工作正常。我将计时器存储为实例变量,以便稍后在必要时使其无效。
class ViewController: UIViewController {
var score: Int = 0
var timer: NSTimer?
override func viewDidLoad() {
super.viewDidLoad()
timer = NSTimer.scheduledTimerWithTimeInterval(1.0, target: self, selector: Selector("incrementTimer"), userInfo: nil, repeats: true)
}
func incrementTimer() {
score++
println(score)
}
}