How do I load a sprite from .sks file to display in my ARSKView?

Viewed 60

I have an ARKit app that uses SpriteKit to display SKNodes that correspond to ARAnchors in the AR session. I am using the ARSKViewDelegate method

func view(_ view: ARSKView, nodeFor anchor: ARAnchor) -> SKNode?

to display the nodes. This works for nodes I create and return in that method, but I have some more complicated nodes that I would like to design in an .sks file and then display for some anchors. When I return a node instantiated from an .sks file in that method the app crashes with an error saying the node is already in the scene (if the node is in the .sks file for the current scene), or already has a parent (if it is in an .sks file for a different scene).

How can I display sprites in ARKit that are drawn in an .sks file?

1 Answers

Try this approach:

if let view = self.view as! SKView? {

    if let scene = SKScene(fileNamed: "mySpriteKitScene") {
            
        guard let clone = scene.childNode(withName: "myRedSprite")?
                               .copy() as? SKSpriteNode
        else { return }

        clone.name = "mySecondRedSprite"
        clone.position.x += 250
        clone.physicsBody = SKPhysicsBody()
        scene.addChild(clone)

        view.presentScene(scene)
    }
}
Related