Search code examples
iosswiftswift3skphysicsbody

Swift Timer SK.wait


I have balls spawning every 3 seconds and I want the balls to spawn faster if the score increases. The problem is my spawnrate stays the same 4 seconds and does not change when my score increases. Thanks for the helps m8s

  var spawnRate : TimeInterval = 4

    var  wait = SKAction .wait(forDuration: spawnRate, withRange: 0.2)

    if score >= 6  {
        spawnRate = 3
        wait = SKAction .wait(forDuration: spawnRate, withRange: 0.2)
    }
     let spawning = SKAction.sequence([wait,spawn])

Solution

  • I would rather refactor the code, and double check that score is really increased , plus cancel previous actions, in case they have not finished after previous launch. My assumption that you produce several actions and they are "accumulated" in the future.

            var spawnRate : TimeInterval
            var wait:SKAction!
    
            if score >= 6  {
                spawnRate = 3
                wait = SKAction .wait(forDuration: spawnRate, withRange: 0.2)
            }
            else {
                spawnRate = 4
                wait = SKAction .wait(forDuration: spawnRate, withRange: 0.2)
            }
    
            let spawningKey ="spawningKey"
            self.spinnyNode?.removeAction(forKey: waitKey)
    
            let spawning = SKAction.sequence([wait,spawn])
    
            self.spinnyNode?.run(spawning, withKey: spawningKey)