Spawning a Spritekit node at a random time

瘦欲@ 提交于 2019-11-30 10:22:57
ABakerSmith

It's not advisable that you use NSTimer with SpriteKit (see SpriteKit - Creating a timer). Instead, to generate random times you could use SKAction.waitForDuration:withRange:

Creates an action that idles for a randomized period of time.

When the action executes, the action waits for the specified amount of time, then ends...

Each time the action is executed, the action computes a new random value for the duration. The duration may vary in either direction by up to half of the value of the durationRange parameter...

To spawn nodes at random times you could combine waitForDuration:withRange with runBlock: together in an SKAction sequence. For example:

// I'll let you adjust the numbers correctly...
let wait = SKAction.wait(forDuration: 3, withRange: 2)
let spawn = SKAction.run {
    // Create a new node and it add to the scene...
}

let sequence = SKAction.sequence([wait, spawn])
self.run(SKAction.repeatForever(sequence))
// self in this case would probably be your SKScene subclass.
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!