swiftxcodesprite-kitfreezeskaction

game freeze for a sec when enemy moving sprit kit swift


this is my time ask questions on stack overflow, so hopefully you guys can understand my problem.

I was building a game for my self using xcode and this is the code that im using to spawn enemy and let them move from right to left of the screen.

      func startHorizonLvl() {
        let spawn = SKAction.run(spawnEnemyHorizon)
        let waitForSec = SKAction.wait(forDuration: 1.2) // here is the problem
        let spawnSequence = SKAction.sequence([waitForSec, spawn])
        let spawnForever = SKAction.repeatForever(spawnSequence)
        
        self.run(spawnForever)
    }

   func spawnEnemyHorizon() {
        
        makePlaceForPlayer()
        enemies.removeAll()

        for index in 0..<possitionArray.count {
            
            if !positionForPlayer.contains(possitionArray[index]){
                let enemy = createEnemy(name: meteoriteName.randomElement()!)
                enemy.position = CGPoint(x: self.size.width * 1.20, y: possitionArray[index])
                enemies.append(enemy)
            }
        }
        
        for enemy in enemies {
            self.addChild(enemy)
            let endPoint = CGPoint(x: -self.size.width * 0.6, y: enemy.position.y)
            let moveEnemy = SKAction.move(to: endPoint, duration: 1.5)
            let deleteEnemy = SKAction.removeFromParent()
            let enemySequence = SKAction.sequence([moveEnemy, deleteEnemy])
            enemy.run(enemySequence)
        }
    }

the move action was running smoothly, but suddenly if I run my code somehow the game freezes for one second then continue with running.

so every time it spawn enemy and move them, at some point freeze whole screen for a sec and then continue with spawning. I think that "let waitForSec = SKAction.wait(forDuration: 1.2)" cause the problem but I don't know why and how to solve it, because it was a working code.


Solution

  • Apparently the problem is not SKAction.wait but physicbody that I have created from texture.

    the link below explain why it happen en solved the problem.

    https://www.hackingwithswift.com/read/36/7/optimizing-spritekit-physics