I have a spriteNode which has a default texture of a black circle and I have placed it in the center of the screen. I also have an array which contains 4 textures. What I want to do is when I click on the screen the black circle in the center randomly picks a SKTexture from the array and changes into set texture. I was thinking a long the lines of the code in the didBeginTouches but I'm stuck on how to truly execute this idea. Thanks for any help. :)
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?'
}
Almost there, change your touchesBegan
to this:
override func touchesBegan(touches: Set<NSObject>, withEvent event: UIEvent) {
let randomIndex = Int(arc4random_uniform(UInt32(array.count)))
choiceBall.texture = array[randomIndex]
}
First line generates a random number from 0 to the size of your array-1 using the arc4random_uniform
function. We also need to convert the size of your array to an Unsigned Integer because Swift is very strict (and rightfully so). We then cast it back to an Integer and use it to access the textures that you already created in your array.