我正在使用 Spritekit 创建棋盘游戏。最初所有的部分(SKSpriteNode)都是隐藏的。它们应该在我触摸它们之后出现吗? 但是由于它们被设置为隐藏,所以当我重写 touchBegan 函数时我无法访问它们。我该怎么办?
override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {
let location = touches.first!.locationInNode(self)
let touchedNode = self.nodeAtPoint(location)
if(touchedNode.name == "pieces"){
if(touchedNode.hidden == true){
touchedNode.hidden = false
}
}
}
最佳答案
您正在尝试在 iOS8 上运行。但这在 iOS9 中已得到修复。如果您在 iOS8 上尝试您的代码,您会发现它有效。这是在 iOS8 上让我恼火的事情之一,因为你可以点击一个隐藏的节点是没有意义的。不过,如果您可以点击一个 alpha 0.0 的节点(也适用于 iOS8),那将是很好的,但这在 iOS9 中也已被修复。因此将 alpha 设置为 0.0 将不起作用。
解决方案
您可以使用 SKNode 的 containsPoint方法:
Returns a Boolean value that indicates whether a point lies inside the parent’s coordinate system.
在您的情况下,父级将是您的 Sprite 。阅读here containsPoint
方法是如何工作的。基本上,containsPoint
不关心节点是否可见,或者它是否有父节点。它只是检查某个点 (location
) 是否位于父节点 (touchedNode
) 的坐标系内。所以这里是你如何使用这种方法来做到这一点:
override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {
let location = touches.first!.locationInNode(self)
self.enumerateChildNodesWithName("pieces") { node, stop in
if node.containsPoint(location) && node.hidden == true {
node.hidden = false
stop.memory = true
}
}
}
在这里,您正在枚举所有片段(我假设 self 是它们的父节点),如果某个节点包含触摸位置并且它是隐藏的,则使其可见(并停止进一步的、不必要的搜索)。
提示:
还可以考虑在此处使用可选绑定(bind):
if let touch = touches.first {
let location = touch.locationInNode(self)
//do your stuff here
}
使用可选绑定(bind)是个好习惯,因为它更安全。
关于ios - 如何通过在 Spritekit 中触摸隐藏的 SKSpriteNode 来检测它们?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36561622/