randomly picking skspritenode node to spawn out of 5 sprites

463 views Asked by At

i have 5 skspritesnodes, i want to spawn 1 random node at a time, i know i have to use arc4random but the examples ive tried dont seem to work. Id like a variable i can then input where ever i need start spawning random looking "enemys"

var bird0 = SKSpriteNode(imageNamed: "back_bird")
var bird1 = SKSpriteNode(imageNamed: "blue_bird")
var bird2 = SKSpriteNode(imageNamed: "green_bird")
var bird3 = SKSpriteNode(imageNamed: "purple_bird")
var bird4 = SKSpriteNode(imageNamed: "orange_bird")

i have the physicsbody set for each, size, ect. everything is all set minus the ability to randomly pick one to come out

2

There are 2 answers

8
Sweeper On

You need to put the sprites in an array. Then, you can access a random element in that array.

Here's a function that returns a random bird.

func randomBird() -> SKSpriteNode {
    let array = [bird0, bird1, bird2, bird3, bird4]
    return array[Int(arc4random_uniform(UInt32(array.count)))]
}

You can also, put all the birds in an array and remove the variables bird0, bird1, bird2 and so on:

let birds = [
    SKSpriteNode(imageNamed: "back_bird"),
    SKSpriteNode(imageNamed: "blue_bird"),
    SKSpriteNode(imageNamed: "green_bird"),
    SKSpriteNode(imageNamed: "purple_bird"),
    SKSpriteNode(imageNamed: "orange_bird")
]

Then birds[Int(arc4random_uniform(UInt32(array.count)))] will get you a random bird.

18
Whirlwind On

As an addition to Sweeper's answer, you can make an extension:

import SpriteKit
import GameplayKit

extension Array {
    var randomElement: Element {
        return self[Int(arc4random_uniform(UInt32(count)))]
    }
}

and use it like this:

class GameScene: SKScene {

    let sprites = [
        SKSpriteNode(color: .brown, size: CGSize(width:100,height:100)),
        SKSpriteNode(color: .blue, size: CGSize(width:100,height:100)),
        SKSpriteNode(color: .red, size: CGSize(width:100,height:100)),
        SKSpriteNode(color: .green, size: CGSize(width:100,height:100)),
        ]

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

        if let randomBird = sprites.randomElement.copy() as? SKSpriteNode{

            if let location = touches.first?.location(in: self){
                randomBird.position = location
                addChild(randomBird)
            }
        }
    }
}