将在场景编辑器中创建的精灵添加到以编程方式创建的场景中

时间:2016-09-17 10:18:38

标签: swift sprite-kit swift3

我想将在场景编辑器中创建的一些精灵节点添加到以编程方式创建的场景中。我试着用以下方式做到这一点:

class hudSKSScene: SKScene {
    var arrows: [SKSpriteNode: SKSpriteNode] = [SKSpriteNode: SKSpriteNode]() 

    // init and other functions here

    func setupArrows(scale: CGFloat) {
        let controllerScene = SKScene(fileNamed: "controllerScene.sks") // scene containing 8 sprites

        let arrowUp = controllerScene?.childNode(withName: "up") as! SKSpriteNode
        let arrowDown = controllerScene?.childNode(withName: "down") as! SKSpriteNode
        let arrowLeft = controllerScene?.childNode(withName: "left") as! SKSpriteNode
        let arrowRight = controllerScene?.childNode(withName: "right") as! SKSpriteNode

        let arrowUpPressed = controllerScene?.childNode(withName: "upPressed") as! SKSpriteNode
        let arrowDownPressed = controllerScene?.childNode(withName: "downPressed") as! SKSpriteNode
        let arrowLeftPressed = controllerScene?.childNode(withName: "leftPressed") as! SKSpriteNode
        let arrowRightPressed = controllerScene?.childNode(withName: "rightPressed") as! SKSpriteNode

        arrows[arrowUp] = arrowUpPressed
        arrows[arrowDown] = arrowDownPressed
        arrows[arrowLeft] = arrowLeftPressed
        arrows[arrowRight] = arrowRightPressed

        for (arrow, arrowPressed) in arrows {
            arrow.zPosition = 2
            arrowPressed.zPosition = 1
            addChild(arrowPressed)
            addChild(arrow)
        }

场景实际上是基于SceneKit的游戏的叠​​加场景。我想以下列方式添加控制器,因为这样我可以轻松定位它们。

我似乎正在导致异常因为我将精灵添加到场景中,当他们已经是创建它们的场景的子节点时(在controllerScene.sks中)。我收到以下消息:

*** Terminating app due to uncaught exception
'NSInvalidArgumentException', 
reason: 'Attemped to add a SKNode which already has a parent: 
<SKSpriteNode> name:'leftPressed' texture:[<SKTexture> 'trianglePressed'

我应该如何创建它们和/或将它们添加到场景中?

0 个答案:

没有答案