2

I'm trying to spawn waves of enemies in a SpriteKit Game. I thought this code would work. how do I make runAllWaves() wait for each wave to complete before calling the next one? (I realize if all else fails i can just increase the waveWait time artificially to count from the beginning instead of the end of each wave)

import SpriteKit

let waveWait =  [5, 10, 10] // pause before each wave
let waveCount = [10, 20, 50] // num. of enemies in each wave
let waveDelay = [3, 2, 1] // pause before each enemy spawns
let waveHealth = [1, 2, 3] // enemy health for each wave

var index:Int = 0

var spawn = SKAction()
var delay = SKAction()
var spawndelay = SKAction()
var repeatspawndelay = SKAction()
var wait = SKAction()
var dowave = SKAction()

var doAllWaves = SKAction()


class GameScene: SKScene {

    override func didMoveToView(view: SKView) {

        print("begin!")

         runAllWaves()
    }

    func runWave(index:Int){

        spawn = SKAction.runBlock({ self.spawnEnemy(index) })
        delay = SKAction.waitForDuration(NSTimeInterval(waveDelay[index]))
        spawndelay = SKAction.sequence([spawn, delay])
        repeatspawndelay = SKAction.repeatAction( spawndelay , count: waveCount[index])

        self.runAction(repeatspawndelay)

    }

    func runAllWaves(){
        runAction(SKAction.sequence([
            SKAction.waitForDuration(NSTimeInterval(waveWait[index])),
            SKAction.runBlock({ self.runWave(index)  }) ]),
            completion: {
                index += 1
                if index < 3 { self.runAllWaves() }})
    }

    func spawnEnemy(index:Int){ print("spawn enemy with health: " + String(waveHealth[index])) }

}
mdamkani
  • 305
  • 2
  • 12

1 Answers1

0

Why don't you implement a runNextWave functionality and call that at the end of runWave? You have arrays that define each wave's attributes; if the 1st element in the array determines that wave's attributes then during runWave you could remove those entries and at the end of runWave simply call runWave again until the arrays are empty or some other condition is met.

Steve Ives
  • 7,894
  • 3
  • 24
  • 55