Reputation: 869
I'm trying to figure it out how to detect if a shapeNode has been pressed, specifically with the LongPress Gesture. Please take a look on the below code. Any idea what is wrong, why I can't see the "Found!" message?
class Test: SKScene {
let longPressGesture = UILongPressGestureRecognizer()
override func didMove(to view: SKView) {
longPressGesture.addTarget(self, action: #selector(GameScene.longPress))
self.view?.addGestureRecognizer(longPressGesture)
let testPath = UIBezierPath(rect: CGRect(x: (view.scene?.frame.midX)!, y: (view.scene?.frame.midY)!, width: 2 * 50.0, height: 2 * 50.0)).cgPath
let testNode = Node.init(path: testPath, nodeName: "TEST")
testNode.fillColor = UIColor.brown
testNode.position = CGPoint(x: (view.scene?.frame.midX)!, y: (view.scene?.frame.midY)!)
self.addChild(testNode)
}
func longPress(_ sender: UILongPressGestureRecognizer) {
let longPressLocation = sender.location(in: self.view)
if sender.state == .began {
for child in self.children {
if let shapeNode = child as? SKShapeNode {
if shapeNode.contains(longPressLocation) {
print("Found!")
}
}
}
} else if sender.state == .ended {
print("ended")
}
}
}
Many thanks for any help!
Upvotes: 2
Views: 218
Reputation: 13665
You are currently calculating tap location in view's coordinate system. In order to work in scene's coordinate system (because SKShapeNode
is added to a scene), you have to convert a tap location from view's coordinate system to scene's coordinate system, like this:
let longPressLocation = convertPoint(fromView: sender.location(in: self.view))
Unrelated to original issue, but a good thing to keep in mind is that forced unwrapping is not that good idea most of the time (sometimes it helps while development phase though), and you should tend to access underlying values of an optionals in a safe way ( using if let syntax for example).
Upvotes: 2