Search code examples
swiftsprite-kitskspritenodeskaction

Spawn nodes at random times combing waitForDuration:withRange and runBlock: in an SKAction sequence


I am making a game with SpriteKit where I have nodes spawning at the top of the screen and falling. However, I want these nodes to spawn at a random time interval between 0.1 and 3 seconds. For example, the first node spawns in 1.3 seconds, the next in 1.8, then 2.5, then 0.8, and so forth forever. I'm not sure how to utilize the waitForDuration function to do this. The code that I currently have is:

let wait = SKAction.waitForDuration(3, withRange: 2)
let spawn = SKAction.runBlock { addTears()
}

let sequence = SKAction.sequence([wait, spawn])
self.runAction(SKAction.repeatActionForever(spawn))

This code freezes my game when I try to run it. I removed the addTears() and put a log, and there was an infinite loop on the log. I need to know how to get rid of this.

The code for my addTears() func is:

func addTears() {
    let Tears = SKSpriteNode (imageNamed: "Tear")
    Tears.position = CGPointMake(Drake1.position.x, Drake1.position.y - 2)
    Tears.zPosition = 3
    addChild(Tears)

//gravity
Tears.physicsBody = SKPhysicsBody (circleOfRadius: 150)
Tears.physicsBody?.affectedByGravity = true

//contact
Tears.physicsBody = SKPhysicsBody (circleOfRadius: Tears.size.width/150)
Tears.physicsBody!.categoryBitMask = contactType.Tear.rawValue
Tears.physicsBody!.contactTestBitMask = contactType.Bucket.rawValue
}

Solution

  • If I remember well, the waitForDuration:withRange: method works like so : if you put a duration of 3 (seconds) and a range of 1 seconds the random value that you get will be between 2 and 4 seconds. That said, you should use those value for what you described : let wait = SKAction.waitForDuration(1.55, withRange: 1.45)

    For the freeze problem, if you pasted your code correctly here the problem come with this line self.runAction(SKAction.repeatActionForever(spawn)) where you should instead be calling your sequence like this : self.runAction(SKAction.repeatActionForever(sequence)).

    PS : At a certain point you still might want to control the amount of tears on screen at the same time.

    Let me know if it helped.