带有子节点的 SKSpriteNode 的触摸检测

sha*_*taf 4 ios sprite-kit swift

我试图在 SKSpriteNode 上触发一个触摸事件,它的子节点被点击。当它触及子节点时,不会触发事件。我发现了一个 hack 工作,.parent但我觉得这不是最有效或最优雅的方法。

请看下面的代码:

override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {

    let touch = touches.first! as UITouch
    let location = touch.locationInNode(self)
    let node = self.nodeAtPoint(location)

    if node is PlanListItem || node.parent is PlanListItem {

        for plan in planListItems as [PlanListItem] {
            plan.selected = false
        }

        // Some more code...
    }
}
Run Code Online (Sandbox Code Playgroud)

非常感谢帮助。

Sim*_*hia 5

您可以在节点子类中执行此操作:

class PlanListItem:SKSpriteNode {

    var isSelected: Bool = false
    override init(texture size etc) {
        //your init
        self.userInteractionEnabled = true
    }

    override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {
        print("PlanListItem touched")
        isSelected = !isSelected
    }
}
Run Code Online (Sandbox Code Playgroud)