Search code examples
iosswiftsprite-kitarc4random

How to choose a random SKShapeNode from an array using arc4random?


I am trying to make my first app using sprite kit and swift. I have created an array and populated it with two shape nodes (shown below.

    //name the properties for enemy 1
    enemy1 = SKShapeNode (rectOfSize: CGSize(width: rectWidth/10, height: rectHeight/10))
    enemy1.position = first
    enemy1.fillColor = UIColor.blackColor()
    enemy1.physicsBody = SKPhysicsBody(rectangleOfSize: CGSize(width: rectWidth, height: rectHeight))
    enemy1.physicsBody?.dynamic = true
    enemy1.physicsBody?.affectedByGravity = false

    //name the properties for enemy 2
    enemy2 = SKShapeNode (rectOfSize: CGSize(width: rectWidth/10, height: rectHeight/10))
    enemy2.position = second
    enemy2.fillColor = UIColor.blackColor()
    enemy2.physicsBody = SKPhysicsBody(rectangleOfSize: CGSize(width: rectWidth, height: rectHeight))
    enemy2.physicsBody?.dynamic = true
    enemy2.physicsBody?.affectedByGravity = false



    //populate the arrays
    arrayOfEnemies1.addObject(enemy1)
    arrayOfEnemies1.addObject(enemy2)

Say I wanted to add one of these nodes to a scene randomly, every 2 seconds. I know to use arc4random, but I am not sure how to do this. Any help would be greatly appreciated. Thanks!


Solution

  • You can create an extension and get a random Array-element like that:

    extension Array {
        func randomElement() -> T {
            let index = Int(arc4random_uniform(UInt32(self.count)))
            return self[index]
        }
    }
    

    Like that:

    var randomElement = arrayOfEnemies1.randomElement()