2

我想知道是否有人可以回答我的问题。我在 Sprite-kit 中使用纹理图集创建了 3 个不同的敌人动画,我想知道是否有一种方法可以在游戏开始时随机选择一个敌人向玩家移动。

TextureAtlas = SKTextureAtlas(named: "zombies.atlas")
for i in 1...TextureAtlas.textureNames.count {
    let Z = "z\(i).png"
    zombieArray.append(SKTexture(imageNamed: Z))
}


TextureAtlas = SKTextureAtlas(named: "baldzomb.atlas")
for i in 1...TextureAtlas.textureNames.count {
    let bald = "baldzomb_\(i).png"
    baldArray.append(SKTexture(imageNamed: bald))
}

TextureAtlas = SKTextureAtlas(named: "crawler.atlas")
for i in 1...TextureAtlas.textureNames.count {
    let Name = "crawler_\(i).png"
    crawlerArray.append(SKTexture(imageNamed: Name))

}
4

1 回答 1

2

你可以这样做:

class GameScene: SKScene {


    let storage = [
        SKSpriteNode(color:.brown, size:CGSize(width: 50, height: 50)),
        SKSpriteNode(color:.white, size:CGSize(width: 50, height: 50)),
        SKSpriteNode(color:.black, size:CGSize(width: 50, height: 50)),
        ]

    func getRandomSprite(fromArray array:[SKSpriteNode])->SKSpriteNode{

        return array[Int(arc4random_uniform(UInt32(array.count)))]
    }

    override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
        super.touchesBegan(touches, with: event)

        let sprite = getRandomSprite(fromArray: storage)

        if let location = touches.first?.location(in: self){

            if let copy = sprite.copy() as? SKSpriteNode {
                //sprite can have only one parent, so I add a copy, just because of better example
                copy.position = location
                addChild(copy)
            }
        }
    } 
}

所以基本上你有一个精灵/纹理/任何数组,你根据数组长度生成随机索引,并返回一个随机元素。您也可以进行扩展,并执行类似yourArray.random.

于 2017-01-16T15:29:29.380 回答