在 SpriteKit 中允许触摸传播

Allow touch propagation in SpriteKit

给定一个 SpriteKit 场景 s,以及一个类型 T 的节点 a 继承自 SKSpriteNode 包含在 s 中,如果 sa 都覆盖任何触摸处理程序,触摸事件将专门在似乎是最顶层(最高 zPosition)的节点上调用。

如果我希望场景及其节点同时执行两个不同的动作,最好使用哪种模式?

在这种情况下,是否更好:

您还有什么建议吗?

更新

给定以下代码:

class Parent: SKScene {
    override func didMove(to view: SKView) {
        self.addChild(Foo())
    }

    override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
        //  React to touch, and, for example, move the scene around
    }
}

class Foo: SKSpriteNode {
    override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
        //  React to touch, and, for example, scale up the node by 60%
    }
}

如果用户点击显示在屏幕上的 Foo 节点,只会调用其 touchesBegan(_, event:) 方法 - Parent 的方法将被忽略。

为了让两个对象能够同时对 touchesBegan(_, event:) 回调作出反应,最好使用什么模式?

我喜欢尽可能多地处理对象 class 中的代码。所以我会处理它的 class 文件中的任何对象触摸代码,并将触摸发送回场景,由场景单独处理。

class Cat: SKSpriteNode {

    var isEnabled = true
    var sendTouchesToScene = true

    override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent!) {

         guard isEnabled else { return }

         //send touch to scene
         if sendTouchesToScene {
             super.touchesBegan(touches, with event)
         }

         //handle touches for cat
    }
}