简化后,我试图弄清楚如何在某个时间段内将10个节点添加到场景中,每个节点之间都间隔了一个随机的时间间隔。

例如:

Loop 10 times:

A. Create and add node to scene

B. Wait some random amount of time, 1-5 seconds

C. Back to A

也很高兴知道何时完成运行,在最后一个节点添加到场景中时让布尔值翻转,但这需要知道最后一个节点何时添加。我不太确定如何做到这一点。我读了一些有关dispatch_after的信息,但这无法解决我在添加节点之间的随机时间问题。

最佳答案

在SpriteKit中,通常使用SKAction及其waitForDuration(withRange:)方法执行此操作。重要的部分将是withRange参数(来自文档的引号):

每次执行动作时,动作都会计算出一个新的随机数
持续时间的值。持续时间在任一方向上可能会有所不同
最多为durationRange参数值的一半。

例如,如果等待时间为3秒,并且range参数设置为2,则将获得2到4秒之间的延迟。

因此,这是您可以执行的操作:

class GameScene: SKScene, SKPhysicsContactDelegate {

    var lastSpawnTime:Date?

    override func didMove(to view: SKView) {

        let wait = SKAction.wait(forDuration: 3, withRange: 4)

        let block = SKAction.run {[unowned self] in
            //Debug
            let now = Date()

            if let lastSpawnTime = self.lastSpawnTime {

                let elapsed = now.timeIntervalSince(lastSpawnTime)

                print("Sprite spawned after : \(elapsed)")
            }
            self.lastSpawnTime = now
            //End Debug

            let sprite = SKSpriteNode(color: .purple, size: CGSize(width: 50, height: 50))
            self.addChild(sprite)
        }

        let sequence = SKAction.sequence([block, wait])
        let loop = SKAction.repeat(sequence, count: 10)

        run(loop, withKey: "aKey")
    }
}

您将在控制台中看到类似以下内容的内容:
Spawning after : 1.0426310300827
Spawning after : 1.51278495788574
Spawning after : 3.98082602024078
Spawning after : 2.83276098966599
Spawning after : 3.16581499576569
Spawning after : 1.84182900190353
Spawning after : 1.21904700994492
Spawning after : 3.69742399454117
Spawning after : 3.72463399171829

关于ios - 定期在场景之间添加一个随机时间间隔的节点,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/42572473/

10-12 14:29