Search code examples
iosswiftsprite-kitskspritenodesknode

Generating new nodes causing frame drop [SpriteKit]


I'm trying to generate new nodes in scene

func generateNewPlatform(inScene: SKScene) {
   for _ in 0...25 {
       let xPosition = randomXPosition()
       let yPosition = randomYPosition()

       let platform = Platform.create(
       platform.position = CGPoint(x: xPosition, y: yPosition)
       inScene.addChild(platform)
   }   
}

I need to generate it every 10 seconds, of course I remove old by

removeFromParent()

But when I do it, it causing frame drop (1-5, depending on the device)

How can I handle this frame drop?


Solution

  • You can push the calculation job into background queue to stop them from blocking the UI, maybe the Platform creation is expensive:

    func generateNewPlatform(inScene: SKScene) {
        var platforms = [Platform]()
        DispatchQueue.global(qos: .userInitiated).async {
            for _ in 0...25 {
                let xPosition = randomXPosition()
                let yPosition = randomYPosition()
    
                let platform = Platform.create(..)
                platform.position = CGPoint(x: xPosition, y: yPosition)
                platforms.append(platform)
            }
            DispatchQueue.main.async {
                platforms.forEach {
                    inScene.addChild($0)
                }
            }
        }
    }