Swift + SpriteKit - Button is clickable even when not visible [duplicate]

余生颓废 提交于 2019-12-24 14:45:52

问题


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?


回答1:


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.



来源:https://stackoverflow.com/questions/36536703/swift-spritekit-button-is-clickable-even-when-not-visible

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!