我在游戏中使用 SKSpriteNode 作为按钮。暂停按钮。
例如:
var pauseButton = SKSpriteNode(imageNamed: "pauseButton")
... some settings (size, position and etc.)...
当我点击一个按钮时,会发生一系列特定的操作。此外,单击后,按钮本身将从场景中删除。
for touch in touches {
let pauseButtonTouch = touch.location(in: self)
if pauseButton.contains(pauseButtonTouch) {
pauseButton.removeAllActions()
pauseButton.removeFromParent()
... some code...
}
但问题就在这里。如果单击该按钮应在的位置,则会启动按下该按钮时应起作用的功能。尽管该节点不在现场。我不明白正在发生的事情的逻辑。请帮我解决问题。为什么舞台上的远程节点点击它就能工作?
对不起我的英语...
您所描述的行为可能会发生,因为即使该节点已从父节点中删除,SpriteKit 中的触摸事件仍然可以检测到触摸。这可能会导致意外的行为。
为了防止出现此问题,您可以添加额外的检查,以确保在执行与其相关的代码之前该按钮仍然存在。这是代码的更新版本:
for touch in touches {
let pauseButtonTouch = touch.location(in: self)
if pauseButton.contains(pauseButtonTouch) {
// Check if the pauseButton is still a child of the scene
if pauseButton.parent != nil {
pauseButton.removeAllActions()
pauseButton.removeFromParent()
// ... some code ...
}
}
}