You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用SKSpriteNode作为暂停按钮的点击异常问题求助

问题原因与解决方法

原因

你虽然把pauseButton从父节点移除了,但变量pauseButton仍然持有这个节点的引用。SKSpriteNode的contains(_:)方法只判断触摸点是否落在节点的坐标范围内,完全不管这个节点有没有被添加到场景树里。所以哪怕节点不在场景中,只要变量没被销毁,点击原位置时contains还是会返回true,触发后续逻辑。

解决办法

有两种简单的处理方式:

  • 方式一:移除节点后清空变量引用
    在调用removeFromParent()之后,把pauseButton设为nil,同时在判断点击时先检查变量是否存在:

    for touch in touches {
        let pauseButtonTouch = touch.location(in: self)
        // 先判断pauseButton是否存在,再检查点击范围
        if let pauseButton = pauseButton, pauseButton.contains(pauseButtonTouch) {
            pauseButton.removeAllActions()
            pauseButton.removeFromParent()
            // 清空引用,避免后续误判
            self.pauseButton = nil
            
            ... 你的其他代码 ...
        }
    }
    
  • 方式二:判断节点是否在场景树中
    在检查点击范围之前,先判断节点是否有父节点(也就是是否在场景里):

    for touch in touches {
        let pauseButtonTouch = touch.location(in: self)
        // 先确认节点还在场景中,再检查点击
        if pauseButton.parent != nil && pauseButton.contains(pauseButtonTouch) {
            pauseButton.removeAllActions()
            pauseButton.removeFromParent()
            
            ... 你的其他代码 ...
        }
    }
    

内容的提问来源于stack exchange,提问作者Nexus S.

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.10 15:47:16