1

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))
}
Martin R
  • 529,903
  • 94
  • 1,240
  • 1,382
Lukas
  • 451
  • 2
  • 13
  • 1
    `let randomNumber = arc4random_uniform(20) + 5`should be *inside* the `getRandomDelay()` function, otherwise it is initialized only once. – Martin R Jan 24 '17 at 19:26
  • Oh yes, thats right, but it still doesn't work :/ – Lukas Jan 24 '17 at 19:31
  • 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 Jan 24 '17 at 19:34
  • 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 Jan 24 '17 at 19:40
  • 1
    The `wait` action is created only once. You may want to use `SKAction.wait(forDuration: withinRange:)` instead. – Martin R Jan 24 '17 at 19:51
  • How do I use withinRange: ? i get an error – Lukas Jan 24 '17 at 19:55
  • Possible duplicate of http://stackoverflow.com/questions/24948731/skaction-how-to-generate-a-random-delay-in-generation-of-nodes – Epsilon Jan 24 '17 at 20:26

1 Answers1

2
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.

Martin R
  • 529,903
  • 94
  • 1,240
  • 1,382