1
votes

I have a sequence where i spawn a obstacle and then wait for a random amount of time, but if I run the game and for example the first random delay 1.4 seconds, but its not just for the first delay it's just all the time 1.4 and it doesn't change (it doesn't have to be 1.4 it's just an example). I have tried to make a function which has a random return value but its doesn't work. I have no idea how i could solve this. Here's my Code for the function with the random return value. If it helps obstSwitch() is the function that creates the Obstacle:

    func getRandomDelay() ->Double {
    let randomNumber = arc4random_uniform(20) + 5
    let randomDelay: Double = Double(randomNumber) / 10
    print(randomDelay)
    return randomDelay
}

and heres the function that get's called when the game started:

func gameStarted() {
    gameAbleToStart = false
    moveLine()
    scoreTimer()
    let runObstSwitch = SKAction.run {
        self.obstSwitch()
    }
    let wait = SKAction.wait(forDuration: getRandomDelay())
    let sequence = SKAction.sequence([runObstSwitch, wait])
    self.run(SKAction.repeatForever(sequence))
}
1
let randomNumber = arc4random_uniform(20) + 5should be inside the getRandomDelay() function, otherwise it is initialized only once. - Martin R
Oh yes, thats right, but it still doesn't work :/ - Lukas
What's the issue? I'm running your function in a Playground now and it seems to print unique values each time. Are you saying that this function doesn't work? - Michael Fourre
The randomDelay only get's printed out once which means it only gets called once, but i want it to be called every time the sequence restarts. - Lukas
The wait action is created only once. You may want to use SKAction.wait(forDuration: withinRange:) instead. - Martin R

1 Answers

2
votes
let wait = SKAction.wait(forDuration: getRandomDelay())
let sequence = SKAction.sequence([runObstSwitch, wait])

creates the wait action once, which is then used in the sequence, so the same amount of idle time is spent between the runObstSwitch actions.

If you want the idle time to be variable, use wait(forDuration:withRange:) instead. For example with

let wait = SKAction.wait(forDuration: 1.5, withRange: 2.0)
let sequence = SKAction.sequence([runObstSwitch, wait])

the delay will be a random number between 1.5-2.0/2 = 0.5 and 1.5+2.0/2 = 2.5 seconds, varying for each execution.