我有一个名为 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/