removeFromParent()奇怪的行为

时间:2018-02-28 12:34:07

标签: swift sprite-kit skspritenode

我对函数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
}()
<{1>}在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在现场不存在。

初​​始:

enter image description here

并点击后:

enter image description here

由于

1 个答案:

答案 0 :(得分:1)

您要做的是检查您触摸的节点是否属于它应该的类型。将您的代码更改为:

override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
    let touch = touches.first!
    if nodeAtPoint(touch.locationInNode(self)) == buttonAds {
        doAds()
        buttonAds.removeFromParent()
    }
}

这应该可以解决问题!

编辑:至于为什么会这样做,你要从场景中移除节点,但它仍然是内存中的一个对象(否则你将无法在其上使用buttonAds.contains(...))所以它的位置仍然存在。

相关问题