Reputation: 65
I am building a shooter game. I would like to spawn a barrier every ten seconds and then delete it after 3 seconds. I think it is something like
let TimeBeforeAdd = DispatchTime.now() + 5
DispatchQueue.main.asyncAfter(deadline: TimeBeforeAdd) {
self.Barrier.position = self.barrierPos
self.addChild(self.Barrier)
self.barrierAdded = true
}
if barrierAdded == true {
let RemoveTime = DispatchTime.now() + 3
DispatchQueue.main.asyncAfter(deadline: RemoveTime) {
self.Barrier.removeFromParent()
self.barrierAdded = false
}
}
but when it runs after ten seconds I get an error saying it added multiple instances of "Barrier" thanks for any help.
Upvotes: 1
Views: 1025
Reputation: 3995
Very cool idea with the dispatch timers. However, there is a much easier way! Here you go:
// Inside of your gamescene:
func spawnThingEveryTenSecondsThenDeleteAfterThree() {
func spawnShootyThing() { /* input your code here */ }
func despawnShootyThing() { /* input your code here */ }
let wait10 = SKAction.wait(forDuration: 10)
let wait3 = SKAction.wait(forDuration: 3)
let spawn = SKAction.run { spawnShootyThing() }
let despawn = SKAction.run { despawnShootyThing() }
let action = SKAction.sequence([wait10, spawn, wait3, despawn])
// If you don't want this action to run forever, then remove this action!
let forever = SKAction.repeatForever(action)
self.run(forever)
}
Upvotes: 2