Swift. SKSpriteNode as a button

40 Views Asked by At

I'm using SKSpriteNode as a button in my game. Pause button.

For example:

var pauseButton = SKSpriteNode(imageNamed: "pauseButton")

... some settings (size, position and etc.)...

When I click on a button, a series of specific actions occur. Also, after clicking, the button itself is removed from the scene.

    for touch in touches {
            
            let pauseButtonTouch = touch.location(in: self)
            if pauseButton.contains(pauseButtonTouch) {
                
                pauseButton.removeAllActions()
                pauseButton.removeFromParent()

                ... some code...

}

But here's the problem. If you click in the place where the button should be, the function that should work when you press this button is launched. Although the node is NOT on scene. I don't understand the logic of what's happening. Please help me solve the problem. Why does a remote node from the stage work if you click on it?

Sorry for my English...

1

There are 1 best solutions below

1
Mitul Pokiya On

The behavior you're describing may occur because the touch event in SpriteKit can still detect touches even if the node has been removed from the parent. This can lead to unexpected behavior.

To prevent this issue, you can add an additional check to ensure that the button is still present before executing the code related to it. Here's an updated version of your code:

for touch in touches {
    let pauseButtonTouch = touch.location(in: self)
    
    if pauseButton.contains(pauseButtonTouch) {
        // Check if the pauseButton is still a child of the scene
        if pauseButton.parent != nil {
            pauseButton.removeAllActions()
            pauseButton.removeFromParent()
            
            // ... some code ...
        }
    }
}