Search code examples
iossprite-kitarkitaranchor

SpriteKit SKLabelNode attached to ARAnchor doesn't appear or appears fullscreen


I'm adding an anchor to my sceneView in the world origin position:

let configuration = ARWorldTrackingConfiguration()
sceneView.session.run(configuration)
sceneView.session.add(anchor: ARAnchor(name: "world origin", transform: matrix_identity_float4x4))
sceneView.presentScene(SKScene())

I then choose to show a SKLabelNode at my anchor position

func view(_ view: ARSKView, nodeFor anchor: ARAnchor) -> SKNode? {
    // Create and configure a node for the anchor added to the view's session.
    let labelNode = SKLabelNode(text: "👾")
    labelNode.horizontalAlignmentMode = .center
    labelNode.verticalAlignmentMode = .center
    return labelNode;
}

When I run the app, and move the camera around, I notice that I either don't see the node at all (I just see the normal camera), or I see the entire screen is purple (as though the label node font size is huge).

I tried adding labelNode.fontSize = 5 but that still has the same problem.

How do I get nodes to display in my SpriteKit scene properly?


Solution

  • When I compare my code with Apple's default SpriteKit + ARKit sample app, the main difference is the line:

    sceneView.presentScene(SKScene())
    

    In their sample code, they use:

    // Load the SKScene from 'Scene.sks'
    if let scene = SKScene(fileNamed: "Scene") {
        sceneView.presentScene(scene)
    }
    

    It appears like SKScene.sks has a size of 750 x 1334 and therefore is equivalent to:

    sceneView.presentScene(SKScene(size: CGSize(width: 750, height: 1334)))
    

    When I update the code to the last line (i.e. give the SKScene a size), everything displays properly. However, I don't think hardcoding the width and height is the right way to do things. I'll ask a separate question about that.