确定手势识别器中触摸的节点

时间:2018-05-15 20:03:25

标签: sprite-kit uigesturerecognizer

我有一个SpriteKit场景,里面可以有数千个不同的节点。我还在场景中实现单击手势识别器,希望一旦触发手势识别器,我就能确定在场景中触摸了哪个节点。目前,我的(非工作)代码如下所示:

@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?")
            }
        }

    }
}

手势识别器正在工作。当我触摸新的地图按钮时,我在控制台中获得了“单击手势识别”,但仅此而已。我在这里做错了什么?

1 个答案:

答案 0 :(得分:0)

  1. 在GameScene文件中,我在didMove方法中创建了我的按钮,如此

    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. 在didMove中添加手势:

    let tapRec = UITapGestureRecognizer()
    tapRec.addTarget(self, action:#selector(GameScene.tappedView(_:) ))
    tapRec.numberOfTouchesRequired = 1
    tapRec.numberOfTapsRequired = 1
    self.view!.addGestureRecognizer(tapRec)
    
  3. 最后实现tappedView方法

    @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?")
            }
        }
    }
    }