The goal of the code is to spawn cards until the sum of the cards hits 17. The code works fine in that case, but I want it to wait 1 second before spawning the other card. The code currently spawns all the cards (and stops until 17 is reached) at once, which I don't want. Here's a simplified version, for reference it is in touchesBegan in SpriteKit:
else if standLabel.contains(touch.location(in: self)) {
let waitForCard = SKAction.wait(forDuration: 1)
while dealerCardValues.sum() <= 16 {
self.run(waitForCard)
spawnCard()
}
The wait for duration doesn't work. Any help is appreciated.
You can use a Timer for this. The timer is called every 1 second, which runs the spawnCard()
function as well as adding 1 to the counter variable. Once counter
has reached 17 we invalidate it to stop it firing again.
So replace this code:
let waitForCard = SKAction.wait(forDuration: 1)
while dealerCardValues.sum() <= 16 {
self.run(waitForCard)
spawnCard()
With this:
var counter = 1
Timer.scheduledTimer(withTimeInterval: 1, repeats: true) { [self] timer in
counter += 1
spawnCard()
if counter == 17 {
timer.invalidate()
}
}