我对函数 removeFromParent
的行为真的很奇怪
lazy var buttonAds: SKSpriteNode = {
let n = SKSpriteNode(imageNamed: "ButtonAds")
n.position = CGPoint(x: size.width / 2, y: 600)
n.zPosition = 100
n.setScale(1.4)
return n
}()
在 didMove(...)
中使用 addChild(buttonAds)
添加此按钮,后者在 touchesBegan
中:
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
let touch = touches.first!
if buttonAds.contains(touch.location(in: self)) {
// ...
doAds()
buttonAds.removeFromParent()
}
}
如果你点击广告按钮,将被删除,但如果再次点击那个地方,这将再次调用函数 doAds()
......很奇怪,buttonAd 不存在场景。
初始:
点击后:
谢谢
最佳答案
你要做的是检查你触摸的节点是否属于它应该的类型。将您的代码更改为:
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
let touch = touches.first!
if nodeAtPoint(touch.locationInNode(self)) == buttonAds {
doAds()
buttonAds.removeFromParent()
}
}
这应该可以解决问题!
编辑:至于为什么会这样,你正在从场景中移除节点,但它仍然是内存中的一个对象(否则你将无法使用 buttonAds.contains(...)
在上面)所以它也仍然存储着它的位置。
关于swift - removeFromParent() 奇怪的行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49029726/