I am getting the error: "Attemped to add a SKNode which already has a parent" when trying to run my game.
If I add the SKSpriteNode locally into the function, it runs fine. But when I try and declare it globally, I get that error. Any help to resolve this error would be great. I assume it has to do with the self.bee.removeFromParent()
but I can't get it to work.
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]))
}