0
votes

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!

1
I haven't programmed with SpriteKit, but I assume you can create an UnsafePointer<EnemyClass> with 4x+ the capacity of the active enemies, and keep two values: offset and count. Then, you'll only need to move all the class references when the count value exceeds the capacity of the pointer. This approach is of course not limited to SpriteKit, but I can't say if it helps your specific case.Andreas detests censorship
"I decided to put all of the enemy sprites in an array and delete the ones who go off the screen" It doesn't sound like a good plot.El Tomato

1 Answers

-1
votes

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()
}