问题
I have a SpriteKit scene that can have thousands of distinct nodes in it. I am also implementing a single-tap gesture recognizer on the scene, in the hopes that I can determine which node has been touched in the scene once the gesture recognizer is triggered. Currently, my (non-working) code looks like this:
@objc func singleTap(_ sender: UIPinchGestureRecognizer) {
print("single tap gesture recognized")
if sender.numberOfTouches == 1 {
let touchPoint = sender.location(in: self.view)
let touchedNode = self.atPoint(touchPoint)
if let name = touchedNode.name
{
if name == "newMapButton"
{
print("newMapButton Touched")
} else {
print("what did you touch?")
}
}
}
}
The gesture recognizer is working. When I touch the new map button I get the "single tap gesture recognized" in the console, but nothing more. What am I doing wrong here?
回答1:
In GameScene file, I created my button in didMove method like so
let btnTest = SKSpriteNode(imageNamed: "button") btnTest.setScale(0.2) btnTest.name = "Button" btnTest.zPosition = 10 btnTest.position = CGPoint(x: 100, y: 200) self.addChild(btnTest)
Adding Gesture in didMove:
let tapRec = UITapGestureRecognizer() tapRec.addTarget(self, action:#selector(GameScene.tappedView(_:) )) tapRec.numberOfTouchesRequired = 1 tapRec.numberOfTapsRequired = 1 self.view!.addGestureRecognizer(tapRec)
Finally implementing tappedView method
@objc func tappedView(_ sender:UITapGestureRecognizer) { if sender.state == .ended { var post = sender.location(in: sender.view) post = self.convertPoint(fromView: post) let touchNode = self.atPoint(post) if let name = touchNode.name { if name == "Button" { print("newMapButton Touched") } else { print("what did you touch?") } } } }
来源:https://stackoverflow.com/questions/50358366/determine-node-touched-in-gesture-recognizer