gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-28 15:05:31 25 4
gpt4 key购买 nike

在下面的代码中,如果我按下 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com