Swift. SKSpriteNode作为按钮

2cmtqfgy  于 2023-09-30  发布在  Swift
关注(0)|答案(1)|浏览(88)

我在游戏中使用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...

}

但问题是如果您在按钮应该在的地方单击,则当您按下此按钮时应该工作的功能将启动。虽然节点不在现场。我不明白发生的事情的逻辑。请帮我解决这个问题。如果单击舞台的远程节点,为什么它会工作?
对不起,我的英语…

rxztt3cl

rxztt3cl1#

您所描述的行为可能会发生,因为即使节点已从父节点中移除,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 ...
        }
    }
}

相关问题