Xcode6迅速.随机使用数组与纹理



我有一个spriteNode,它有一个默认的黑色圆圈纹理,我把它放在屏幕的中心。我也有一个包含4个纹理的数组。我想做的是,当我点击屏幕上的黑色圆圈在中心随机选择一个SKTexture从数组和更改为设置纹理。我在想很长的代码行在didbegin触摸,但我卡住了如何真正执行这个想法。谢谢你的帮助。:)

var array = [SKTexture(imageNamed: "GreenBall"), SKTexture(imageNamed: "RedBall"), SKTexture(imageNamed: "YellowBall"), SKTexture(imageNamed: "BlueBall")]
override func didMoveToView(view: SKView) {
    var choiceBallImg = SKTexture(imageNamed: "BlackBall")
    choiceBall = SKSpriteNode(texture: choiceBallImg)
    choiceBall.position = CGPointMake(self.frame.size.width / 2, self.frame.size.height / 2)
    self.addChild(choiceBall)
}
override func touchesBegan(touches: Set<NSObject>, withEvent event: UIEvent) {
    choiceBall.texture = SKTexture(imageNamed: arc4random(array))
    //error: Cannot assign a value of type 'SKTexture!' to a value of type 'SKTexture?' 
}

差不多了,把你的touchesBegan改成这样:

override func touchesBegan(touches: Set<NSObject>, withEvent event: UIEvent) {
        let randomIndex = Int(arc4random_uniform(UInt32(array.count)))
        choiceBall.texture = array[randomIndex]
    }

第一行使用arc4random_uniform函数生成一个从0到数组大小的随机数-1。我们还需要将数组的大小转换为Unsigned Integer,因为Swift是非常严格的(这是正确的)。然后我们将它转换回一个Integer,并使用它来访问你已经在数组中创建的纹理。

最新更新