Search code examples
swiftsprite-kitskspritenodetouchesbegan

touchesBegan on a node to delete it


per exemple, I have a SKSpriteNode generated in a function named "generateNode" every seconds, and I want to call it in the touchesBegin function to detect when the user touch it, and if the user touch it, the node is deleted.

I tried to call the node in this function, but it is impossible, Xcode doesn't detect it in this function.

How to do that ?

Thanks you.


Solution

  • You can remove a particular node in the following way.

    First set the node.name property at the place where you add it.

    func generateNode() {
        // your node creation code
        node.name = "generatedNode"
        //add your node.
    }
    

    Then in touchesBegan, you can remove the touched node if the name of the node is the name you set.

    override func touchesBegan(touches: NSSet, withEvent event: UIEvent) {
    
        let touch = touches.anyObject() as UITouch?
        if let location = touch?.locationInNode(self)
        {
            for node in self.nodesAtPoint(location)
            {
                if node.name == "generatedNode"
                {
                    node.removeFromParent()
                }
            }
    
        }
    }