随机选择skspritenode节点以产生5个精灵

时间:2016-12-26 00:21:44

标签: swift xcode sprite-kit skspritenode arc4random

我有5个skspritesnodes,我想一次产生1个随机节点,我知道我必须使用arc4random但是我尝试的例子似乎不起作用。我喜欢变量,然后我可以输入我需要开始产生随机寻找的东西" 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")

我为每个,大小等设置了物理实体。一切都是设置减去随机选择一个出来的能力

2 个答案:

答案 0 :(得分:2)

作为Sweeper的答案的补充,您可以进行扩展:

import SpriteKit
import GameplayKit

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

并像这样使用它:

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

答案 1 :(得分:1)

你需要将精灵放在一个数组中。然后,您可以访问该数组中的随机元素。

这是一个返回随机鸟的函数。

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

您还可以将所有的鸟类放入数组并删除变量bird0bird1bird2等等:

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

然后birds[Int(arc4random_uniform(UInt32(array.count)))]会给你一只随机鸟。