给定 SpriteKit
场景s
,和一个节点a
类型 T
继承自 SKSpriteNode
包含在 s
中,如果两者都是 s
和a
覆盖任何触摸处理程序,触摸事件仅在最顶层(最高 zPosition
)节点上调用。
如果我希望场景及其节点同时执行两个不同的操作,最好使用什么模式?
在这种情况下,最好是:
- 让场景通过检索触摸发生位置处的节点来处理所有触摸?
- 有一个
Touchable
场景将实现的协议(protocol),并让任何节点通过假设的touched(_ nodeID: Int)
向场景发送标识符方法? - 让所有子节点都引用静态
TouchHandler
将执行这两个操作的对象?
您还有什么建议吗?
更新:
给出以下代码:
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:)
使用react同时回调?
最佳答案
我喜欢在对象类中处理尽可能多的代码。因此,我将处理其类文件内的任何对象触摸代码,并将触摸发送回场景以由场景单独处理。
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
}
}
关于ios - 允许 SpriteKit 中的触摸传播,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61010180/