尝试添加已存在父错误的SKNode

时间:2015-02-09 09:38:23

标签: ios objective-c swift sprite-kit

我收到错误:“在尝试运行我的游戏时,尝试添加已有父级的SKNode”。

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

让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]))

}

1 个答案:

答案 0 :(得分:11)

您无法两次添加同一SKNode的单个实例。这就像说一个人可以同时存在于两个地方。 当您在Bee node函数范围之外全局创建addBee时,您试图一次又一次地添加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

}