为什么我在swift xcode中出现此错误? “试图添加已经拥有父母的SKNode”

时间:2015-04-11 16:18:29

标签: xcode swift skaction

我不知道为什么我一直收到此错误消息。你能看看我的代码并告诉我我做错了什么吗?我出于某种原因在arrowLeft上出错了。

由于未捕获的异常'NSInvalidArgumentException'而终止应用程序,原因:'尝试添加已经有父名称的SKNode:名称:'(null)'纹理:[

class GameScene: SKScene, SKPhysicsContactDelegate {

let arrowLeft = SKSpriteNode(imageNamed: "leftarrow")
let arrowRight = SKSpriteNode(imageNamed: "rightarrow")

func moveArrowInstructions() {

    arrowLeft.position = CGPointMake(self.size.width / 4.0, self.size.height / 2)
    arrowLeft.zPosition = 20
    arrowRight.position = CGPointMake(self.size.width / 1.3, self.size.height / 2)
    arrowRight.zPosition = 20
    arrowLeft.setScale(0.4)
    arrowRight.setScale(0.4)

    arrowRight.alpha = 0
    arrowLeft.alpha = 0

    let moveArrowToRight = SKAction.moveByX(150 + arrowRight.size.width, y: 0, duration: 2.5)
    let moveArrowToLeft = SKAction.moveByX(-150 - arrowLeft.size.width, y: 0, duration: 2.5)
    let fadeInArrows = SKAction.fadeInWithDuration(1.0)
    let fadeOutArrows = SKAction.fadeOutWithDuration(1.0)
    let sequenceLeftArrow = SKAction.sequence([fadeInArrows, moveArrowToLeft, fadeOutArrows])
    let moveLeftArrowRepeat = SKAction.repeatActionForever(sequenceLeftArrow)
    let sequenceRightArrow = SKAction.sequence([fadeInArrows, moveArrowToRight, fadeOutArrows])
    let moveRightArrowRepeat = SKAction.repeatActionForever(sequenceRightArrow)

    arrowLeft.runAction(moveLeftArrowRepeat)
    arrowRight.runAction(moveRightArrowRepeat)




    addChild(arrowLeft)
    addChild(arrowRight)
}


    override func touchesBegan(touches: Set<NSObject>, withEvent event: UIEvent) {

        func moveArrows() {

        let generateArrows = SKAction.sequence([
            SKAction.runBlock(self.moveArrowInstructions),
            SKAction.waitForDuration(3.5)])
        let endlessAction = SKAction.repeatActionForever(generateArrows)
        runAction(endlessAction)
    }

    var touch: UITouch = touches.first as! UITouch
    var location = touch.locationInNode(self)
    var node = self.nodeAtPoint(location)


    if(node.name == "startgame") {
        arrowRight.removeFromParent()
        arrowLeft.removeFromParent()






    }

2 个答案:

答案 0 :(得分:2)

您正尝试多次向场景添加相同的节点。

快速修复可能是检查节点是否已添加到场景中。像这样:

if arrowLeft.parent == nil && arrowRight.parent == nil{
   addChild(arrowLeft)
   addChild(arrowRight)
}

答案 1 :(得分:1)

每次触摸都会不断向父母添加相同的孩子

的addChild(arrowLeft)     的addChild(arrowRight)

设置场景时

需要在某个区域