2017-01-16 115 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