Search code examples
swiftsprite-kitskspritenode

How to keep node count of invaders in space game stable in xcode spritekit with swift?


I was programming a space game where the enemies are spawned off the screen at a random position, but I got stuck when the node count increased because I made a new enemy sprite in the func override update()

then I decided to put all of the enemy sprites in an array and delete the ones who go off the screen.

Is there a more efficient way of doing this? thanks in advance!


Solution

  • Particularly i think that it's not a good idea to put this code on the update func as it will run your code before render every frame...so it will run it like 60 times per second.

    A better solution is create a Function to spawn enemies and call it with a timer. First of all declare a variable in your class to handle the enemy count and the timer:

    var enemies = 0
    var enemyTimer = Timer()
    
    
    func spawn(){
    //YOUR SPAWN CODE
    enemies += 1 //Will increase 1 enemy to the enemies variable every time this function is called
    }
    

    to start the timer:

     enemyTimer = Timer.scheduledTimer(timeInterval: YOUR TIME INTERVAL TO SPAWN ENEMIES, target: self, selector: #selector(YOUR_CLASS_NAME.spawn), userInfo: nil, repeats: true)
    

    Start the timer when the game starts, invalidate it when the game ends and when you move to another scene! This timer will call the spawn func every "n" seconds!

    About the out of screen you may use the update func:

          if scene?.frame.contains(enemyNode.position){
            //nothing here
        }else{
    //Out of screen, do stuff here...
    enemyNode.removeFromParent()
    }