如何使用arc4random从数组中选择随机的SKShapeNode? [英] How to choose a random SKShapeNode from an array using arc4random?
本文介绍了如何使用arc4random从数组中选择随机的SKShapeNode?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试使用Sprite Kit和Swift创建我的第一个应用程序。我创建了一个数组,并在其中填充了两个形状节点(如下所示。
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)
假设我想每2秒将其中一个节点随机添加到场景中。我知道要使用arc4random,但是我不确定该怎么做。任何帮助将不胜感激。谢谢!
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!
推荐答案
您可以创建扩展名并获得如下所示的随机数组元素:
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]
}
}
就像这样:
var randomElement = arrayOfEnemies1.randomElement()
这篇关于如何使用arc4random从数组中选择随机的SKShapeNode?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文