Asphys
Asphys

Reputation: 185

How to detect touch in spritekit?

I have a sprite and I would like to print some text if that sprite is pressed on. Every tutorial that I have found on that seems to be outdated. How is this possible?

It should be something like this:

if Sprite is touched {
    print("Some Text")
}

Upvotes: 2

Views: 3805

Answers (2)

Loanb222
Loanb222

Reputation: 851

In the touchesBegan function or touchesEnded you can add this code

for touch: AnyObject in touches {
      let location = touch.locationInNode(self)
      if sprite.containsPoint(location) {
         print("Some Text")
      }
}

Upvotes: 1

Luca Angeletti
Luca Angeletti

Reputation: 59496

If you have a custom class for your Sprite just override the touchesBegan method

Example

class Player: SKSpriteNode {

    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
        userInteractionEnabled = true
    }
    override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {
        print("Did touch Player sprite")
    }
}

Don't forget to set userInteractionEnabled = true

Upvotes: 5

Related Questions