ios - 带子节点的SKSpriteNode的触摸检测

标签 ios swift sprite-kit

我正在尝试在点击其子节点的 SKSpriteNode 上触发触摸事件。当它接触到子节点时,不会触发该事件。我发现了一种使用 .parent 的 hack 方法,但我觉得这不是最有效或最优雅的方法。

请看下面的代码:

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...
    }
}

非常感谢帮助。

最佳答案

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

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
    }
}

关于ios - 带子节点的SKSpriteNode的触摸检测,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39446405/

相关文章:

ios - 如何判断一个自定义类是可变的还是不可变的?

ios - 如何让敌人拥有独立的生命?

节点上的 Swift SpriteKit 声音

iOS7 Sprite Kit 如何禁用对 Sprite 的触摸以使其成为 "tap through"?

ios - 如果年份是特定值,则执行不同的功能

ios - tabBar默认和自定义图像对齐

ios - 为 BOOL 变量编写 getter 和 setter

ios - 构建具有不同用例的 View Controller 的最佳方法?

ios - Swift UITableViewCell IBOutlets 未显示在 StoryBoard 中

swift - 如何使用 arc4random_uniform 从数组中随机选择一个值