Exterminate nodes at random times by combing waitForDuration: withRange and runBlock: in SKAction sequence

I am making a game with SpriteKit where I have nodes popping up at the top of the screen and dropping. However, I want these nodes to appear at a random time interval between 0.1 and 3 seconds. For example, the first node appears at 1.3 seconds, the next at 1.8, then 2.5, then 0.8, etc. Forever and ever. I'm not sure how to use the waitForDuration function for this. The code I have now:

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 addTears () and put the log and there was an infinite loop in the log. I need to know how to get rid of this.

Code for my addTears () function:

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
}

      

+2


source to share


1 answer


If I remember well, the method waitForDuration:withRange:

works like this: if you set the duration to 3 (seconds) and the range to 1 second, then the random value you get will be between 2 and 4 seconds. However, you must use this value for what you described:let wait = SKAction.waitForDuration(1.55, withRange: 1.45)

For problems with freezing, if you insert your code here, the problem is with this line self.runAction(SKAction.repeatActionForever(spawn))

, where instead you must call sequence

as follows: self.runAction(SKAction.repeatActionForever(sequence))

.



PS: At some point, you can still control the number of tears on the screen at the same time.

Let me know if it helped.

+5


source







All Articles