如何随机选择SKSpriteNode?

时间:2015-07-13 06:11:56

标签: swift random

我想从随机选择4个敌人并在场景中呈现它。为此我已经做到了:

func enemyPicker() -> SKSpriteNode {
    var enemyArray = [mouse, robot, drone, block, bird]
    var countArray = UInt32(enemyArray.count)
    var pickOneEneny = arc4random_uniform(countArray)
    var randomElement = Int(pickOneEnemy)

    return enemyArray.randomElement
}

但Xcode对我说SKSpriteNode does not have a member named randomElement。它肯定没有,但我怎么能对我的功能说我需要它来挑选并从阵列中将随机的Int分配给一个真正的敌人?

我尝试使用this answer,但这对我不起作用。我也试图改变 - > SKSpriteNode到SKTexture,String和“T”,并没有任何运气。

我的SpriteNodes声明为:

var mouse = SKSpriteNode() 
let mouseAtlas = SKTextureAtlas(named: "mouse")
var mouseArray = [SKTexture]()
mouseArray.append(mouseAtlas.textureNamed("mouse_0"));
mouseArray.append(mouseAtlas.textureNamed("mouse_1"));
mouseArray.append(mouseAtlas.textureNamed("mouse_2"));

mouse = SKSpriteNode(texture: mouseArray[0]);
self.mouse.position = CGPointMake(CGRectGetMaxX(self.frame), CGRectGetMidY(self.frame) - 138)
self.mouse.size = CGSizeMake(self.mouse.size.width, self.mouse.size.height + mouse.size.height / 2)

self.mouse.name = "mouse"
self.addChild(mouse)

1 个答案:

答案 0 :(得分:1)

func enemyPicker() -> SKSpriteNode {
    let enemyArray = [mouse, robot, drone, block, bird]
    return enemyArray[Int(arc4random_uniform(UInt32(enemyArray.count)))]
}