试图添加一个已经有父错误的 SKNode

Attemped to add a SKNode which already has a parent error

我在尝试 运行 我的游戏时遇到错误:"Attemped to add a SKNode which already has a parent"。

如果我在本地将 SKSpriteNode 添加到函数中,运行没问题。但是当我尝试全局声明它时,我得到了那个错误。解决此错误的任何帮助都会很棒。我认为它与 self.bee.removeFromParent() 有关,但我无法让它工作。

let bee = SKSpriteNode(imageNamed: "Bee")

runAction(SKAction.repeatActionForever(
    SKAction.sequence([
        SKAction.runBlock(addBee),
        SKAction.waitForDuration(0.5)
        ])
    ))

func addBee() {

bee.name = "Bee"
let actualY = random(min: 0, max: size.height+bee.size.height ) // random

bee.position = CGPoint(x: size.width + bee.size.width/2, y: actualY)
self.addChild(bee)

let slopeToPlayer = (bee.position.y - player.position.y) / (bee.position.x - player.position.x)
let constant = bee.position.y - slopeToPlayer * bee.position.x

let finalX : CGFloat = bee.position.x < player.position.x ? 500.0 : -500.0 // Set it to somewhere outside screen size

let finalY = constant +  slopeToPlayer * finalX

let distance = (bee.position.y - finalY) * (bee.position.y - finalY) + (bee.position.x - finalX) * (bee.position.x - finalX)
let beeSpeed = random(min: CGFloat(50), max: CGFloat(150))
let timeToCoverDistance = sqrt(distance) / beeSpeed

let moveAction = SKAction.moveTo(CGPointMake(finalX, finalY), duration: NSTimeInterval(timeToCoverDistance))
let removeAction = SKAction.runBlock { () -> Void in
    self.bee.removeFromParent()
}
bee.runAction(SKAction.sequence([moveAction,removeAction]))

}

您不能将同一 SKNode 的单个实例添加两次。这就像说一个人可以同时存在于两个地方。 当您在 addBee 函数的范围之外全局创建 Bee node 时,您试图一次又一次地添加 Bee 的相同实例。

如果您想添加多个节点,您应该创建单独的节点实例。这就是为什么在函数内本地创建它们的原因。

func addBee() {

    let bee = SKSpriteNode(imageNamed: "Bee")
    bee.name = "Bee"
    addChild(bee)
}

获取碰撞节点的参考。

func didBeginContact(contact: SKPhysicsContact) {

    var bodyA : SKPhysicsBody!
    var bodyB : SKPhysicsBody!

    if contact.bodyA.categoryBitMask < contact.bodyB.categoryBitMask
    {
        bodyA = contact.bodyA!
        bodyB = contact.bodyB!
    }
    else
    {
        bodyB = contact.bodyA!
        bodyA = contact.bodyB!
    }

    // The two nodes that have collided
    let node1 = bodyA.node 
    let node2 = bodyB.node

}