SpriteKit - Why SKNode's are not being touch detected

1.3k views Asked by At

I have reviewed countless references to try to understand why my scene is not behaving the way i expected it to, such as this.

Here is my very simple SKScene (2 child nodes):

  • The scene has a SpriteNode (which covers the entire scene as a background image). This has a zPosition = 0.
  • The scene has a 2nd node (SKNode) which itself has another child (up to 2 levels). This has a zPosiiton - 2.
  • ALL nodes have .userInteractionEnabled = false

Issue:

When i click anywhere all i see is that the 1st child (SpriteNode) is touched. The 2nd child (SKNode) is never touch-detected.

Note that the z-ordering of the Nodes are being rendered as I expect them. It is the touch-detection that doesnt appear to be working.

Snippet of my touchesBegan method:

       for touch in touches {
            let touchLocation = touch.locationInNode(self)
            let sceneTouchPoint = self.convertPointToView(touchLocation)
            let touchedNode = self.nodeAtPoint(sceneTouchPoint)
            if (touchedNode.name != nil) {
                print("Touched = \(touchedNode.name! as String)")
            }
        }
2

There are 2 answers

0
Joel Mata On BEST ANSWER

I had a similar issue (background in z: 999 + spawning "ducks" nodes in z: <999) that I solved with the following code in Swift 4:

override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
    let touch:UITouch = touches.first!
    let positionInScene = touch.location(in: self)
    let touchedNodes = self.nodes(at: positionInScene)
    for touch in touchedNodes {
        let touchName = touch.name
        if (touchName != nil && touchName!.hasPrefix("pato_")) {
            touch.removeFromParent()
        }
    }
}
0
Undead-Earth .com On

I had several layers of nodes because I used a mask over my game with buttons to make selections and move forward. I had issues with the buttons not working until I made a "startState:Bool = true" and updated this to false when the start screen was clicked through. I then had each of my buttons on that start page to have && startState==true for there clicks to be taken. It may be that your clicks are being recorded - but its not the node you think you are using. I would put print("NodeXXX") on each entry in touches and give it a unique name so you can see where the touches are actually happening.

Hope that helps.

Best regards, mpe