0
votes

I'm trying to make things happen when I press a sprite however I'm having an issue trying to get the touch to be recognized correctly.

class GameScene: SKScene {

var optDiceSprite = SKSpriteNode()

override func didMoveToView(view: SKView) {
    createOptSprite()
}

override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {
    for touch in touches {
        let location = touch.locationInNode(self)
        let node = nodeAtPoint(location)

        print("NAME OF NODE: \(node.name)")

        if (node == optDiceSprite) {
            print("WHY U NO WORKY!")
        }
    }
}

func createOptSprite() {
        optDiceSprite = SKSpriteNode(imageNamed: "sound_off")
        optDiceSprite.userInteractionEnabled = true
        optDiceSprite.position = CGPoint(x: CGRectGetMaxX(self.frame) - 30, y: CGRectGetMinY(self.frame) + 30)
        optDiceSprite.setScale(0.5)
        addChild(optDiceSprite)
}

It's not kicking off the print statement. I declare the sprite globally, create and position it before this code is ran in the touchesBegan method.

What I'm trying to do is every time the user switches touches a sound icon sprite, it will toggle sound effects on and off.

Any help is appreciated!

1

1 Answers

2
votes

Try this instead

   class GameScene: SKScene {

        var optDiceSprite = SKSpriteNode()

        override func didMoveToView(view: SKView) {
        createOptSprite()
   }

    override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {
        for touch in touches {
           let location = touch.locationInNode(self)
           let node = nodeAtPoint(location)

           print("NAME OF NODE: \(node.name)")

           if (node == optDiceSprite) {
                print("WHY U NO WORKY!")
              }
          }
     }

  func createOptSprite() {
    optDiceSprite = SKSpriteNode(imageNamed: "sound_off")
    optDiceSprite.setScale(0.5)
    optDiceSprite.position = CGPoint(x: CGRectGetMaxX(self.frame) - 30, y: CGRectGetMinY(self.frame) + 30)
    addChild(optDiceSprite)
  }