user3808792
user3808792

Reputation: 103

Swift + Sprite Kit Touch Detection

I am just wondering how to remove an SKSprite Node from the scene. This is what I have so far:

override func touchesBegan(touches: NSSet, withEvent event: UIEvent) {
    /* Called when a touch begins */


    for touch: AnyObject in touches {
        let location = (touch as UITouch).locationInNode(self)
        if let theName = self.nodeAtPoint(location).name {
            if theName == "monster" {

                monster! .removeFromParent()



            }
        }
    }
}

I am creating lots of these monsters on the screen but when I tap on one of them it doesn't do anything. If I trying adding println("touched") it tells me that it has been touched.

Upvotes: 2

Views: 5209

Answers (2)

user4233369
user4233369

Reputation:

When you do monster.removeFromParent() this does not remove the touched node because monster is not a reference to the touched node. To remove the touched node you can use the following code:

for touch in touches {
    let location = (touch as UITouch).locationInNode(self)
    if let theMonster = self.nodeAtPoint(location) 
        if theMonster.name == "monster" {
            theMonster.removeFromParent()
        }
    }
}

Upvotes: 3

Rashad
Rashad

Reputation: 11197

Are you keeping track of your monsters? If not please keep track of those by adding these to a Mutable Array. Also add unique name to each sprite.

Then just compare the object with your array and remove that object. Hope this helps.. :)

Upvotes: 0

Related Questions