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

◇◆丶佛笑我妖孽 提交于 2020-01-06 15:43:14

问题


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!


回答1:


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


来源:https://stackoverflow.com/questions/30157647/how-to-choose-a-random-skshapenode-from-an-array-using-arc4random

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!