swift - 子类节点,但想检测场景中的触摸

标签 swift sprite-kit

我有一个名为 LocationNode 的子类节点,它启用了触摸功能。看起来像这样。

class LocationNode: SKSpriteNode, CustomNodeEvents {
func didMoveToScene() {
    self.isUserInteractionEnabled = true
}
}

我没有在这个子类文件中重写touchesBegan,因为我想在实际场景文件中像这样控制所有的触摸事件:

override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
    let touchLocation = touches.first!.location(in: self)
    let touchedNode = self.atPoint(touchLocation)

    //if touchedNode.name != nil {
        print("touched")
    //}
}

但是,当我尝试这样做时,它不起作用。如何控制场景文件中子类节点的触摸事件?

编辑:

这是我的覆盖函数在场景中的样子。

    override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
    let touchLocation = touches.first!.location(in: self)
    let touchedNode = self.atPoint(touchLocation)
    print("TOUCHED")
}

最佳答案

您可以在您的自定义类中实现以下代码,在本例中为 LocationNode,以向父类“返回触摸”,然后您可以在两个地方处理触摸(也到主场景):

override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
        for touch in touches {
            print("touched!")
        }
        guard let parent = self.parent else { return }
        parent.touchesBegan(touches, with: event)
}

关于swift - 子类节点,但想检测场景中的触摸,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41832455/

相关文章:

xcode - SpriteKit 纹理图集 : Define Image Format (RGBA4444, RGB565,...)

ios - 如何在 Swift 3 中将 SKSpriteNode 合并到 SKTexture 中以形成新的 SKSpriteNode?

ios - 如何获取 NSManagedObject 的主键值?

ios - 登录后保存 userDefault token

design-patterns - 将关卡添加到 SpriteKit 应用程序

iOS:我可以使用已经用 Adob​​e Animate 创建的 Texture Atlas 吗?

swift - 关闭弹出窗口的正确方法是什么?

ios - 如何正确分配SKSpriteNode空间?

ios - 在 iOS 上拍摄照片时出现随机错误

ios - SpriteKit 在转换到新场景时收到有关 UIElements 的错误