3

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)"
            print(imageName)
            dad.texture = SKTexture(imageNamed:imageName)
        }
        else{
            index += 1
            imageName += "\(index)"
            print(imageName)
            dad.texture = SKTexture(imageNamed:imageName)
            //moves dad
            dad.runAction(moveLeft) // moves image
            index = 0
        }
        //change the image name back to dad
        imageName = "dad"
    }
}
0

1 Answer 1

1

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")

arraySprites.append(dad)
Sign up to request clarification or add additional context in comments.

1 Comment

thanks! I initialized the array and the images inside the class, then append dad to the array inside of the didMoveToView function

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.