Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

swift call function multiple times inside update

I create a game via SpriteKit. in the game every few second a ball spawn to the screen (via function) and the player has to blow them up. now, I want to check the player level via his score so if the score is bigger than 10 the spawnBall function will be executed twice (so 2 ball will spawn on the screen) an so on. I tried to to it via the update fun (that will "read" the player score and depends on the score will call the spawnBall function). Unfortunately when I do it the screen is spawn with million (or so) balls in few seconds (as I said I want it to call the function every few seconds and increase the call while the score is X). I really don't have any idea how to do it. here is my code:

override func update(_ currentTime: CFTimeInterval) {

    if (self.score <= 10){
        spawnBalls()
    }

    if (self.score > 10 && self.score <= 20){
        spawnBalls()
        spawnBalls()
    }

    if (self.score > 20){
        spawnBalls()
        spawnBalls()
        spawnBalls()
    }

    if (self.subscore == 3) {
        _ = randomBallColorToBlow()
        self.subscore = 0
    }
}

func spawnBalls() {
    let wait = SKAction.wait(forDuration: 1)
    let action = SKAction.run {
        self.createBall()
    }
    run(SKAction.repeatForever((SKAction.sequence([wait, action]))))
}

how can I do it without using the update function??

like image 940
omerc Avatar asked Sep 10 '26 10:09

omerc


1 Answers

you are calling spawn balls 60 times a second by calling it in your update func. try just checking if a certain requirement is met to upgrade to a higher spawn rate in your update but keep the calls out of the update func.

private var upgradedToLevel2 = false
private var upgradedToLevel3 = false

//called somewhere probably in a start game func
spawnBalls(duration: 1.0)

override func update(_ currentTime: CFTimeInterval) {

    if (self.score > 10 && self.score <= 20) && !upgradedToLevel2 {
        //this prevents the if loop from running more than once
        upgradedToLevel2 = true 
        self.removeAction(forKey: "spawn")
        spawnBalls(duration: 0.5)
    }

    if (self.score > 20) && !upgradedToLevel3 {
        //this prevents the if loop from running more than once
        upgradedToLevel3 = true
        spawnBalls(duration: 0.33)
    }
}

func spawnBalls(duration: Double) {

    let wait = SKAction.wait(forDuration: duration)
    let action = SKAction.run { self.createBall() }
    let repeater = SKAction.repeatForever(SKAction.sequence([wait, action]))

    run(repeater, withKey: "spawn")
}
like image 101
Ron Myschuk Avatar answered Sep 12 '26 17:09

Ron Myschuk