blvckcode blvckcode - 1 year ago 97
Swift Question

How to create an array of SKSpriteNodes using Swift?

I've designed my program so that each time the user touches the screen, the sprite's image and position changes. I want to be able to make an array of SKSpriteNodes. I've seen a similar post, but they used a for-in loop. Is it possible to create a SKSpriteNode at initialization?

GameScene: SKScene {
// make an array of images that you will possibly change in the future

// calls the image
let dad = SKSpriteNode(imageNamed: "dad0")
var imageName = "dad"

let moveLeft = SKAction.moveByX(-10, y:0 , duration: 0.01)

...assuming that I already placed dad sprite node onto screen...

override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {

// when index is zero, sprite is dad0.
// Change image to dad1 (lifted leg), don't change position
if index == 0{
index += 1 //image names are dad0, dad1
imageName += "\(index)"
dad.texture = SKTexture(imageNamed:imageName)
index += 1
imageName += "\(index)"
dad.texture = SKTexture(imageNamed:imageName)
//moves dad
dad.runAction(moveLeft) // moves image
index = 0
//change the image name back to dad
imageName = "dad"

Answer Source

An array of SKSpriteNode could be simply: [SKSpriteNode] (Array in swift composed by elements of SKSpriteNode type)

So , everytime you want to add a new SKSpriteNode you can do it with:

var arraySprites :[SKSpriteNode] = [SKSpriteNode]()

let dad : SKSpriteNode! 

dad = SKSpriteNode(imageNamed: "dad0")

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download