Search code examples
swiftsprite-kitsknode

Swift + SpriteKit - Button is clickable even when not visible


I seem to be having problems with one of the Nodes on my scene.

I have a button:

 func createAttackButton() {
    attackButton.zPosition = 1
    attackButton.anchorPoint = CGPointZero
    attackButton.position = CGPointMake(20, 20)
    attackButton.size = CGSize(width: 150, height: 40)

    addChild(attackButton)

 }

This function is called when contact is made with the enemy.

To run a function from this button I use the touchesBegan() func:

 override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {

    for touch: AnyObject in touches {
        let location = touch.locationInNode(self)

        if attackButton.containsPoint(location) {

            print("Attack Button Clicked")

        }
    }
}

Once the enemy has been destroyed I remove the Attack Button Node:

 attackButton.removeFromParent()

However, in the area where the attack button appears, once it has been removed, that area is still clickable.

Any ideas?


Solution

  • It seems that whether or not the node is added to the parent, containsPoint method will behave the same. Means, it will always return true if the given point lies inside of parent's (in your case, button's) coordinate system.

    You can check this by initializing the attackButton without adding it to the scene. If you tap in the lower left corner of the scene, the message from the touchesBegan will be still printed.

    I guess, this is happening because of the fact that each node has its position property set to CGPoint(0,0) by default. Also, in your case, the button has its size. And it will have its size and position set even if it's not added to its parent (or if removed from its parent) because it is obviously defined as a property and there is a strong reference to it.