Reputation: 1048
I have around 120 SKSpriteNode
s.
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
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:
children
array just as if you have wrote this instead: self.children.first { $0.name == "BlueSquare1" }
nil
. That means it can never be called using the childNode(withName: String)
. Instead, use self.children.first { $0.name == nil }
.Upvotes: 1