Determine Node Touched in Gesture Recognizer

南笙酒味 提交于 2019-12-24 20:36:23

问题


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:


  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)
    
  2. Adding Gesture in didMove:

    let tapRec = UITapGestureRecognizer()
    tapRec.addTarget(self, action:#selector(GameScene.tappedView(_:) ))
    tapRec.numberOfTouchesRequired = 1
    tapRec.numberOfTapsRequired = 1
    self.view!.addGestureRecognizer(tapRec)
    
  3. 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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!