我对 SpriteKit 和 Swift 有疑问。
我在场景代码的不同点添加 SKSpriteNode
- 其中一些是可点击的,一些不是。我使用可点击的节点作为播放器的菜单。因此,例如 - 如果他单击 InventoryButtonNode
,他就会跳转到 Inventory。在 Inventory 中,他可以触摸 PlayButton 并跳回游戏。所以,首先我添加节点:
override func didMoveToView(view: SKView) {
PlayButton = SKSpriteNode(imageNamed: "PlayButton")
PlayButton.size = CGSize(width: 100, height: 100)
PlayButton.position = CGPoint ... // not important
PlayButton.zPosition = 200
PlayButton.name = "PlayButton"
self.addChild(PlayButton)
InventoryButton = SKSpriteNode(imageNamed: "InventoryButton")
InventoryButton.size = CGSize(width: 100, height: 100)
InventoryButton.position = CGPoint ... // different position than PlayButton
InventoryButton.zPosition = 200
InventoryButton.name = "PlayButton"
self.addChild(InventoryButton)
在覆盖函数 touchesBegan
中,我使用了这些“菜单”节点,例如这里的 InventoryButton-Node
。
if InventoryButton.containsPoint(touch.locationInNode(self)) {
print("Show Inventory")
ShowInventory()
}
现在在 ShowInventory() 函数中,我想从 View 中删除那些“菜单”按钮,以便我可以添加其他节点来显示玩家的库存。
func ShowInventory(){
PlayButton.removeFromParent()
InventoryButton.removeFromParent()
}
如果我构建并运行它,节点将被删除 - 或者更确切地说 - 它们将变得不可见。
因为,如果我现在触摸 InventoryButton
的位置,我仍然会打印“Show Inventory” - 因此即使节点不可见,该功能仍会对我的触摸使用react。
我的问题是,我有 4 个不同的函数,例如 ShowInventory()
.. 我有 ShowGame()
等等 .. 我想要这些函数完全移除节点和“触摸”能力..
我需要一个可以完全删除节点的函数..
我什至尝试过:
func ShowInventory(){
self.removeAllChildren()
}
我得到一个没有任何节点的灰色背景......但仍然 - 如果我触摸库存按钮位置,我会调用函数并打印“显示库存”......这令人沮丧。
最佳答案
这是因为您检查按下哪个按钮没有考虑按钮是否可见。
即使一个节点已经从它的父节点中移除,它仍然有一个position
和size
。 containsPoint:
使用这两个属性来确定点是否在节点中
修复它的最简单方法是先检查按钮是否有父节点,然后再检查按钮是否包含该点。
if InventoryButton.parrent != nil && InventoryButton.containsPoint(touch.locationInNode(self)) {
print("Show Inventory")
ShowInventory()
}
关于Swift SKSpriteNode 将消失但仍可点击,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36021792/