Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 !

like image 602
fredericdnd Avatar asked Nov 29 '15 17:11

fredericdnd


1 Answers

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)

    }   
}
like image 153
Rachel Avatar answered Oct 26 '22 06:10

Rachel