Pro Grammer
Pro Grammer

Reputation: 1

Make loop execute at random intervals with Spritekit

I'm trying to make a program that adds multiple nodes at a random intervals from 0 to 3 seconds. Can you please explain why I need runAction or SKAction in the first place? And why I can't put the random function I made inside this block? Also, is there a way to convert the loop into a while loop so that I can break it more easily?

This is what I have right now:

let wait = Double(random(min:0.0, max:3.0))

runAction(SKAction.repeatActionForever(
        SKAction.sequence([
            SKAction.runBlock(addNode),
            SKAction.waitForDuration(wait)
            ])

I tried this but it doesn't seem to work

      var wait = Double(random(min:0.0, max:3.0))

    var x = true
    while x == true
        {
            addNode()
            SKAction.waitForDuration(wait)
            wait = Double(random(min:0.0, max:3.0))
    }

Upvotes: 0

Views: 60

Answers (1)

Knight0fDragon
Knight0fDragon

Reputation: 16827

waitForDuration takes in a range parameter that will do +- 1/2 value of the range specified, so if you specify 2, it will do a ranged difference -1 <-> 1 to your specified time

E.G. duration 5 seconds range 2

Results

Waits 4

Waits 5.5

Waits 4.47

Waits 4.93

Waits 5.99

To answer the specific question

SKAction.waitForDuration(1.5, withRange 3)

Upvotes: 3

Related Questions