如何使用Swift创建SKSpriteNodes数组?

时间:2016-05-23 07:52:38

标签: arrays swift sprite skspritenode

我设计了我的程序,以便每次用户触摸屏幕时,精灵的图像和位置都会发生变化。我希望能够创建一个SKSpriteNodes数组。我见过similar post,但他们使用了for-in循环。是否可以在初始化时创建SKSpriteNode?

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)

...假设我已将爸爸精灵节点放到屏幕上......

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

1 个答案:

答案 0 :(得分:1)

SKSpriteNode数组可能只是:[SKSpriteNode](swift中的数组由SKSpriteNode类型的元素组成)

因此,每当您想要添加新的SKSpriteNode时,您都可以使用:

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

let dad : SKSpriteNode! 

dad = SKSpriteNode(imageNamed: "dad0")

arraySprites.append(dad)