2017-01-16 4 views
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)) 

} 

// 
+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この回答は正しいです。これらの敵のいずれかを無作為に選ぶことに適切に反応します。私はあなたが敵のランダムな選択に関係していないはずのtextureAtlasの構築を投稿した理由を理解していません。他に何をしようとしていますか? –

+0

@AlessandroOrnano、あなたがtextureAtlasを見る理由は、私の質問に答えた後にタイトルを編集したためです。 – sicvayne

関連する問題