swift - 即使调用 Swift SpriteKit 中的 removeFromParent() 按钮仍然有效

标签 swift sprite-kit

在下面的代码中,如果我按下 removeButton 按钮会消失,但它仍然有效。也许我应该让 if 语句为假,但我不知道该怎么做。

class GameScene : SKScene {

    var button : SKSpriteNode!
    var removeButton : SKSpriteNode!
    var image : SKSpriteNode!

    override func didMove(to view: SKView) { 
        createButton()
        createRemoveButton()
    }

    func createButton() {
        button = SKSpriteNode(imageNamed: "button")
        button.position = CGPoint(x: -300,y: 0)
        self.addChild(button)
    }

    func createRemoveButton() {
        removeButton = SKSpriteNode(imageNamed: "removeButton")
        removeButton.position = CGPoint(x: 300,y: 0)
        self.addChild(removeButton)
    }

    override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) {
        let touch = touches.first
        let touchLocation = touch!.location(in: self)
        if button.contains(touchLocation) {
            image = SKSpriteNode(imageNamed: "image")
            image.position = CGPoint(x: 0,y: 300)
            self.addChild(image)
        }
        if removeButton.contains(touchLocation) {
            button.removeFromParent()
        }
    }
    override func update(_ currentTime: TimeInterval) {
    }
}

最佳答案

您需要了解 ARC(自动引用计数)以及保留实例所需的条件。

在您的情况下,您保留了按钮,这意味着它不会从内存中删除。

现在,当您从父级移除按钮时,按钮的框架仍然完全相同,唯一不同的是 button.parent 现在是 nil

当您调用 button.contains(touchLocation) 时,这将通过,因为您不关心按钮是否在现场,您所做的只是检查 >touchLocation 在按钮的 frame 内。

最快的解决方法是检查父级:

override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) {
    let touch = touches.first
    let touchLocation = touch!.location(in: self)
    if button.parent == self && button.contains(touchLocation) {
        image = SKSpriteNode(imageNamed: "image")
        image.position = CGPoint(x: 0,y: 300)
        self.addChild(image)
    }
    if removeButton.contains(touchLocation) {
        button.removeFromParent()
    }
}

但实际上,您需要学习如何更好地管理您的资源。我建议尝试查找有关 ARC 工作原理的教程。

关于swift - 即使调用 Swift SpriteKit 中的 removeFromParent() 按钮仍然有效,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48530419/

相关文章:

ios - Swift & SpriteKit - 如何在 GameScene 中呈现警报 View

ios - 接触时从场景中移除 Sprite

swift - 如何复制或克隆 Sprite ?

ios - 快速将自定义包对象序列化为 json 字符串到 Bool

iOS 15 - Xcode 13-RC 警告 : -[NSKeyedUnarchiver validateAllowedClass:forKey:]

ios - 在 UITableViewController 中使用 UITextView - 点击外部以关闭键盘

ios - Swift 3 - 如何将 Real Result<Object> 转换为泛型类型 [T]

ios - 控制缩放行为 ARKit

ios - 为什么使用更大的显示器时游戏速度变慢 (fps)?

ios - Swift 3.0 迁移后的 Project-Swift.h 文件正在编译相同的函数数百次,编译时间为 7 分钟