barracuda
barracuda

Reputation: 1048

Get SKSpriteNode by name Swift 2, Xcode 7

I have around 120 SKSpriteNodes.

I have a matrix of the position of each sprite, in this matrix I store the name of the sprite. I need to move a sprite to a new position.

How can I grab the following sprite by name:

let sprite = SKSpriteNode(imageNamed:"BlueSquare")
sprite.name = "BlueSquare1"


// ... in another function
let newsprite = // ???? GET SKSpriteNode by name BlueSquare1????

How can I get a node by name and use the SKAction.moveTo function on that sprite?

Upvotes: 2

Views: 940

Answers (1)

0-1
0-1

Reputation: 773

Calling a child node:

If you have added your sprite to the SKScene, you will be able to call it later for use.

self.addChild(sprite)

If you want to call it in another method, you can use this:

let sprite = self.childNodeWithName("BlueSpuare1") as? SKSpriteNode

Note the use of casting SKNode to SKSpriteNode. You only need to do this when accessing properties unique to SKSpriteNode (i.e. texture or colorBlendFactor). This means that using the SKAction.moveTo method can be used on a SKNode and doesn't need to be casted.


How to move the sprite:

import SpriteKit
class GameScene: SKScene {
    func didMove(to: SKView) {
        let sprite = SKSpriteNode(imageNamed:"BlueSquare")
        sprite.name = "BlueSquare1"
        addChild(sprite)
        moveSquare("BlueSquare1") // Place this line anywhere you want it called
    }

    func moveSquare(_ square: String) {
        let moveTo: CGPoint = // to position
        let time: Double = // duration
        childNode(withName: square).moveTo(moveTo, duration: time)
    }
}

Final Tips:

  • Note that calling the names of children is not recursive. Swift will not look into the names of grandchildren, etc.
  • If 2 child nodes have the same name, Swift will find the first one inside the children array just as if you have wrote this instead: self.children.first { $0.name == "BlueSquare1" }
  • If you do not give your node a name, it's default value is nil. That means it can never be called using the childNode(withName: String). Instead, use self.children.first { $0.name == nil }.

Upvotes: 1

Related Questions