Sam Sam - 1 year ago 63
Swift Question

How to properly manage groups of sprites onscreen

I'm building my first game in Swift and I wanted to know how to go about handling multiple on screen sprites at once. My game pushes sprites on to screen with

continuously, so there are many active at once. I realized that I didn't have a proper way of simultaneously affecting all of them- like if I wanted to affect a physics property of all enemy sprites at once. So far I created an empty array
var enemySprites = [enemyType1]()
at the begining of
and have been
the sprite instances to it instead of using
to draw them directly to the scene. However, I'm not able to simply loop through and draw them to screen with:

for enemy in enemySprites{

this bit of code is in the
override func update(currentTime: CFTimeInterval)
function, so maybe I'm just misplacing it? Any help on how to go about this would be great!

Answer Source


Here's some sample code to update enemies when your lives reach 0:

First, we set a property observer on the lives property so we can call a function when you lose all lives:

var lives = 3 {
    didSet {
        if lives == 0 {

And then a function to enumerate over all the enemies and change each one's velocity to (0, 0):

func update enemies() {
        enumerateChildNodesWithName("type1") {
            node, stop in
            let enemy = node as! SKSpriteNode
            enemy.physicsBody?.velocity = CGVector(dx: 0, dy: 0)
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download