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

只愿长相守 提交于 2019-12-10 10:29:28

问题


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
}

回答1:


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.



来源:https://stackoverflow.com/questions/30851619/spawn-nodes-at-random-times-combing-waitfordurationwithrange-and-runblock-in-a

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!