ios - 允许 SpriteKit 中的触摸传播

标签 ios sprite-kit skspritenode game-development skscene

给定 SpriteKit场景s ,和一个节点a类型 T继承自 SKSpriteNode包含在 s 中,如果两者都是 sa覆盖任何触摸处理程序,触摸事件仅在最顶层(最高 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/

相关文章:

ios - 我应该如何处理通过多个 channel 分发的应用程序的推送通知?

ios - UIScrollView 中的辅助功能问题

swift - 将 SKSpriteNode 旋转到另一个 SKSpriteNode

swift - 将背景移动到无限滚动有助于 Swift Sprite Kit

iphone - 同时播放相同的声音? (快速, Sprite 套件)

ios - 持久存储错误的内存管理错误

iphone - iOS SDK - iPhone 音频插孔如何与连接的电缆交互?

ios - 设置 SKSpriteNode.phyisicsBody.categoryBitMask 时出现 EXC_I386_INVOP 错误

ios - 检测 Sprite 纹理内的触摸而不是整个框架 iOS Swift SpriteKit?

ios - SpriteKit 动画因 validateIndexBuffer 而崩溃