Search code examples
swiftanimationsprite-kittexture-atlas

Randomize different enemy in spritekit to move towards player


I was wondering if anyone could answer my question. I have created 3 different enemy animations with texture atlas in Sprite-kit and I was wondering if there is a way that an enemy is randomly picked to move towards the player as soon as the game begins.

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

}

Solution

  • You can do it like this:

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

    So basically you have an array of sprites/textures/whatever and you generate random index based on array length, and return a random element. You can make an extension as well, and do something like yourArray.random.