【问题标题】:Xcode6 Swift. arc4random using array with texturesXcode6 斯威夫特。 arc4random 使用带有纹理的数组
【发布时间】:2015-07-19 15:16:04
【问题描述】:

我有一个 spriteNode,它有一个黑色圆圈的默认纹理,我把它放在屏幕的中心。我还有一个包含 4 个纹理的数组。我想要做的是当我点击屏幕时,中心的黑色圆圈随机从数组中选择一个 SKTexture 并更改为设置的纹理。我一直在思考 didBeginTouches 中的代码行,但我一直坚持如何真正执行这个想法。谢谢你的帮助。 :)

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?' 

}

【问题讨论】:

    标签: arrays xcode swift sprite-kit arc4random


    【解决方案1】:

    差不多了,把你的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 并使用它来访问您已经在数组中创建的纹理。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-07-22
      • 2017-03-24
      • 2020-07-31
      • 1970-01-01
      • 2018-02-13
      • 1970-01-01
      • 2016-02-08
      • 2017-11-13
      相关资源
      最近更新 更多