2017-01-16 82 views
2

我想知道是否有人可以回答我的問題。我用Sprite-kit中的紋理地圖創建了3種不同的敵人動畫,我想知道是否有一種方法,一旦遊戲開始,敵人就會隨機選擇朝着玩家移動。在spritekit中隨機化不同的敵人向玩家移動

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

} 

// 
+0

你可以發表你曾嘗試過的嗎 –

+0

我還沒有嘗試過,我正在考慮在我的spawnEnemy函數中創建一個「possibleEnemy」函數。任何想法實現這一目標? – sicvayne

回答

1

你可以這樣說:

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的事情。

+0

我在頂部添加了我的代碼 – sicvayne

+1

@ The1steven2此答案正確。它對隨機挑選任何這些敵人做出正確迴應。我不明白你爲什麼發佈紋理貼圖的構造,它應該對隨機選擇的敵人沒有影響。你還想做什麼? –

+0

@AlessandroOrnano,你看到textureAtlas的原因是因爲我在回答問題後編輯了標題。 – sicvayne