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 }
.