So I've got two timers, one that increases the score and one that spawns enemies. I used a notification to invalidate the timers, and then I'm using another one to recreate the timers. When I quit and then open the app, there are two sets of enemies being spawned on top of each other. I think timerRecreate = true and also the regular timers in GameScene are also being called.
GameViewController.swift file:
class GameViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
NSNotificationCenter.defaultCenter().addObserver(self, selector: Selector("pauseTimers:"), name:UIApplicationWillResignActiveNotification, object: nil)
NSNotificationCenter.defaultCenter().addObserver(self, selector: Selector("startTimers:"), name:UIApplicationDidBecomeActiveNotification, object: nil)
}
func pauseTimers(notification : NSNotification) {
println("Observer method called")
timer.invalidate()
scoretimer.invalidate()
}
func startTimers(notification : NSNotification) {
println("Observer method called")
timerRecreate = true
}
Code for timers in GameScene.swift
override func didMoveToView(view: SKView) {
//Spawn timer for enemy blocks
timer = NSTimer.scheduledTimerWithTimeInterval(0.4, target: self, selector: Selector("spawnEnemies"), userInfo: nil, repeats: true)
//Timer for keeping score
scoretimer = NSTimer.scheduledTimerWithTimeInterval(0.1, target: self, selector: Selector("scoreCounter"), userInfo: nil, repeats: true)
}
override func update(currentTime: CFTimeInterval) {
/* Called before each frame is rendered */
if timerRecreate == true {
//Spawn timer for enemy blocks
timer = NSTimer.scheduledTimerWithTimeInterval(0.4, target: self, selector: Selector("spawnEnemies"), userInfo: nil, repeats: true)
//Timer for keeping score
scoretimer = NSTimer.scheduledTimerWithTimeInterval(0.1, target: self, selector: Selector("scoreCounter"), userInfo: nil, repeats: true)
timerRecreate = false
}
}
I think the problem is when you initially open the app, be that after quitting out of it or opening it for the first time, timerRecreate is set to true as well as the regular spawning of blocks so two sets of blocks are spawned at the same time. How can I fix this?
Fixed it! I hope...
Anyway heres what I did. I created another boolean called timerz and set it to false when the DidBecomeActive notification was made. At the same time, timeRecreate is set to true. This guarantees that both timer sets arent running at the same time. In the update function inside the if statement on whether timRecreate was true, I set timeRecreate to false and timerz to true. So the timers are recreated and then it switches back to to old way of spawning them. I also put this old method of spawning them inside an if statement on whether timerz was true or false.