Search code examples
iosswifttouchscenekituitapgesturerecognizer

Convert touch location of UITapGestureRecognizer for SpriteKit - Swift


I created a game with a SceneKit scene into a UIViewController.

I implemented a UITapGestureRecognizer like this :

// TAP GESTURE

let tapGesture = UITapGestureRecognizer(target: self, action: "handleTap:")
sceneView.overlaySKScene?.view!.addGestureRecognizer(tapGesture)

And the handleTap function :

func handleTap(sender: UIGestureRecognizer) {

    if sender.state == UIGestureRecognizerState.Ended {

        var touchLocation = sender.locationInView(sender.view)

        touchLocation = self.view.convertPoint(touchLocation, toView: self.view)

        let touchedNode = sceneView.overlaySKScene?.nodeAtPoint(touchLocation)

        if touchedNode == myNode {

            // DO SOMETHING

        }

    }

}

Imagine that myNode's position is (x: 150.0, y: 150.0). The problem is that the touchPosition.y is at the opposite of the y position of myNode's y position.

How can I invert y position of the touch ?

Thanks !


Solution

  • Try this instead, its accurate for me:-

    override func didMoveToView(view: SKView) {
    
         let tap:UITapGestureRecognizer = UITapGestureRecognizer(target: self, action: Selector("tap:"))
         tap.numberOfTapsRequired = 1
    
         view.addGestureRecognizer(tap)
    }
    
    func tap(sender:UITapGestureRecognizer){
    
        if sender.state == .Ended {
    
            var touchLocation: CGPoint = sender.locationInView(sender.view)
            touchLocation = self.convertPointFromView(touchLocation)
    
        }   
    }