How do you reference multiple sprites with the same name in sprite kit?

Viewed 61
import SpriteKit
var ground: SKSpriteNode?

class GameScene: SKScene {
    
   
    override func didMove(to view: SKView) {
        ground = self.childNode(withName: "ground") as? SKSpriteNode
        let move = SKAction.moveBy(x: 1000, y: 1000, duration: 10)
        ground?.run(move)
    
}
    
}

I have 3 sksprite nodes with the name "ground". But only one of them runs the action move. How do I make them all run the action move? Thank you for any help.

2 Answers

You want to use enumerateChildNodes, this cycles through all nodes and any nodes whose name matches the withName part, the containing code is run. Any node we do find while searching, we just assign it to a constant called groundNode (can be any name), and make it an SKSpriteNode. From there, you can do anything SKSpriteNode related, in your case we run a moveBy action on it.

  enumerateChildNodes(withName: "ground") {
                   (node, _) in
                let groundNode = node as! SKSpriteNode
                let move = SKAction.moveBy(x: 1000, y: 1000, duration: 10)
                groundNode.run(move)
  }
Related