Search code examples
swiftsprite-kituikit

Is it possible to get multiple SKNodes with UITapGestureRecognizer?


I currently have multiple balls all on the same SKScene. I handle all touches and gestures within GameScene. Below is the code I use to detect which node was touched, which works.

What I am unsure of, since there are always some touchesMoved when using this on a real device, is there anyway possible for more than one node to receive a tap at the same time? If so I obviously would need to write my code differently.

@objc func tappedView(_ sender:UITapGestureRecognizer) {

    if sender.state == .ended{
        let point : CGPoint = sender.location(in: self.view)
        var post = sender.location(in: sender.view)
        post = self.convertPoint(fromView: post)
        
        if let touchNode = self.atPoint(post) as? MyBall{
            //the declaration below is just so I have somewhere to stop in the debugger
            var x = 1 
        }
     }
}

Solution

  • Use nodes(at:) to get multiple nodes at a point.

    @objc func tappedView(_ sender:UITapGestureRecognizer) {
    
        if sender.state == .ended{
            let point : CGPoint = sender.location(in: self.view)
            var post = sender.location(in: sender.view)
            post = self.convertPoint(fromView: post)
            
    
            for touchNode in self.nodes(at:post){
                //the declaration below is just so I have somewhere to stop in the debugger
                var x = 1 
            }
         }
    }
    

    https://developer.apple.com/documentation/spritekit/sknode/1483072-nodes