我正在創建一個SpriteKit遊戲,該遊戲根據經過的時間量進行更新。遊戲使用NSTimer
及其scheduledTimerWithTimeInterval
方法產生敵人,每2.0秒調用一次spawnEnemy
函數。爲什麼我的SpriteKit update()函數創建多個NSTimers?
當5秒鐘過去後,應該有一個非常短暫的間歇,以防止新的敵人產卵以顯示水平變化動畫。
當最初5秒鐘到達時,一切正常,直到有條件的地方self.nextLevelDelayTicker == 100
。一旦滿足這個條件,"YOLO"
字符串只在控制檯中被觸發一次。但是,我假設正在創建NSTimer
的多個實例並將其存儲在self.timer
之內,因爲在調用self.resumeGame()
以創建新的計劃的計時器之後會產生大量的敵人。
爲什麼會發生這種情況的任何想法,即使我在我的條件下設置的標誌只能調用self.resumeGame()
函數一次?
func resumeGame() {
// Start game timer
// Need a way to access ib action of pause button
self.timer = NSTimer.scheduledTimerWithTimeInterval(2.0, target: self, selector: "spawnEnemy", userInfo: nil, repeats: true)
}
override func update(currentTime: CFTimeInterval) {
/* Called before each frame is rendered */
if gameTicker.isActive == true {
gameTicker.increment()
}
// If gameTicker is equal to 5 seconds, increase enemy amount
if gameTicker.getTimePassed() % 500 == 0 {
self.enemyAmount += 1
self.timer?.invalidate()
levelCount += 1
gameTicker.isActive = false
}
// If level has been completed and last ghost has been killed, activate next level scene
if gameTicker.isActive == false && enemyArray.count == 0 {
self.nextLevelDelayTicker.increment()
if self.nextLevelDelayTicker.getTimePassed() == 100 {
print("YOLO")
self.gameTicker.isActive = true
self.nextLevelDelayTicker.reset()
self.resumeGame()
}
}
}
下面的答案值得考慮,但就你的問題而言,你創建了你的計時器變量並放置在更新中。每次更新被調用時,一個新的定時器被創建,因此多個定時器的想法雖然下面的答案是好的,但我喜歡使用skaction並在那裏創建我的定時器,並以適當的變量而不是更新方法調用它們。但那只是我。 –