grahamcracker1234
grahamcracker1234

Reputation: 609

How to detect a touch of a child sprite

I know that this may have been asked before, but nothing has exactly what I need. Now imagine this situation, I have a game and in this game there is an SKSpriteNode called Background in the middle of the screen. On that Background Sprite there is a child called Button. How would I detect if a touch was ended on the Button. If somebody could please help me with the code for the TouchesEnded function, as well as maybe explain in further detail what is happening. Thank you, swift would be ideal, but I guess I can read Objective-C if I need to.

ADDED INFO

Here are my two sprites:

let buttonBackground = SKSpriteNode(imageNamed: "Button Background.png") //The parent node of button
let soundOn = SKSpriteNode(imageNamed: "Sound On.png") //The button being pressed, which is a child of buttonBackground

Here is my touchesEnded function:

override func touchesEnded(touches: Set<UITouch>, withEvent event: UIEvent?) {
    // Called when a touch begins

    for touch in touches {
        let location = touch.locationInNode(self)
        let nodeAtTouch = self.nodeAtPoint(location)
        let touchedSprite = nodeAtTouch as! SKSpriteNode

        if touchedSprite == button {
            print("YES")
        }
    }
}

Upvotes: 0

Views: 194

Answers (1)

Pranav Wadhwa
Pranav Wadhwa

Reputation: 7746

When a touch ends, get the node from that point

override func touchesEnded(touches: Set<UITouch>, withEvent event: UIEvent?) {
    for touch in touches {
        let location = touch.locationInNode(self)
        let something = self.nodeAtPoint(location)
        let skNode = something as! SKSpriteNode
        //Do something with skNode
    }
}

Upvotes: 2

Related Questions