子节点,但想要检测场景中的触摸

时间:2017-01-24 15:49:43

标签: swift sprite-kit

我有一个名为LocationNode的子节点,其中启用了触摸。看起来像这样。

class LocationNode: SKSpriteNode, CustomNodeEvents {
func didMoveToScene() {
    self.isUserInteractionEnabled = true
}
}

我没有覆盖此子类文件中的touchesBegan,因为我想在实际场景文件中控制所有这样的触摸事件:

override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
    let touchLocation = touches.first!.location(in: self)
    let touchedNode = self.atPoint(touchLocation)

    //if touchedNode.name != nil {
        print("touched")
    //}
}

然而,当我尝试这样做时,它不起作用。如何在场景文件中控制子类节点的触摸事件?

编辑:

这是我的覆盖功能在场景中的样子。

    override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
    let touchLocation = touches.first!.location(in: self)
    let touchedNode = self.atPoint(touchLocation)
    print("TOUCHED")
}

1 个答案:

答案 0 :(得分:3)

您可以在自定义类中实现以下代码,在本例中为LocationNode,以便为父类提供“返回触摸”,然后您可以处理这两个位置的触摸(也是主要的场景):

override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
        for touch in touches {
            print("touched!")
        }
        guard let parent = self.parent else { return }
        parent.touchesBegan(touches, with: event)
}