I'm making a game where I have a node that is spawning and falling from the top of the screen. However I want to make the nodes spawn at random time intervals between a period of 3 seconds. So one spawns in 1 second, the next in 2.4 seconds, the next in 1.7 seconds, and so forth forever. I am struggling with what the code should be for this.
Code I currently have for spawning node:
let wait = SKAction.waitForDuration(3, withRange: 2)
let spawn = SKAction.runBlock { addTears()
}
let sequence = SKAction.sequence([wait, spawn])
self.runAction(SKAction.repeatActionForever(spawn))
The code for my addTears() function 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
}
It's not advisable that you use
NSTimer
with SpriteKit (see SpriteKit - Creating a timer). Instead, to generate random times you could useSKAction.waitForDuration:withRange:
To spawn nodes at random times you could combine
waitForDuration:withRange
withrunBlock:
together in anSKAction
sequence. For example: