Repeat action on a SpriteNode

63 Views Asked by At

I would like to repeatedly show one of the two games cards, whenever the user touches the deckOfCards.

I got it working once so far, but when I tap on the deckOfCards again, the card does not change. Trying this with 10 or more card names, didn't work either.

class GameScene: SKScene {

let cardname = ["card2", "ace"]
let randomNumber = Int(arc4random_uniform(13))
var deckOfCards = SKSpriteNode()
var yourCard = SKSpriteNode()

override func didMove(to view: SKView) {
    deckOfCards = self.childNode(withName: "deckOfCards") as! SKSpriteNode
    yourCard = self.childNode(withName: "yourCard") as! SKSpriteNode
}

override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
    self.view?.endEditing(true)

    for touch: AnyObject in touches {

        let location = touch.location(in: self)
        let node : SKNode = self.atPoint(location)
        if node.name == "deckOfCards" {
            yourCard.texture = SKTexture(imageNamed: "\(cardname[randomNumber])")
        }
    }
}
1

There are 1 best solutions below

0
On BEST ANSWER

randomNumber is a constant outside of touchesBegan. It never changes. Put it inside touchesBegan.

override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
    self.view?.endEditing(true)

    for touch: AnyObject in touches {
        let location = touch.location(in: self)
        let node = self.atPoint(location)
        let randomNumber = Int(arc4random_uniform(13))

        if node.name == "deckOfCards" {
            yourCard.texture = SKTexture(imageNamed: "\(cardname[randomNumber])")
        }
    }
}