Search code examples
iossprite-kitarkitskscenearscnview

Custom SKScene is not displaying in AR


I have created SKScene via SpriteKit tested it like 2D app. Here is my viewController. Everything works fine.

class GameViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()

        let scene = GameScene(size: CGSize(width: 2560, height: 2560))
        scene.anchorPoint = CGPoint(x: 0.5, y: 0.5)
        scene.scaleMode = .aspectFit

        let skView = self.view as! SKView
        skView.showsFPS = true
        skView.showsNodeCount = true
        skView.presentScene(scene)
    }
}

SKScene (GameScene) is quite simple, its structure: SKScene - SKNode - SKTileMapNode.

My goal is to display this Scene in AR on surface. In AR app I faced a problem that my custom SKScene is not displaying, it's just blank screen. custom SKScene I decided to check default SKScene: I created static Grid (Map) in .sks file and loaded it instead of my dynamic custom SKScene. It displays perfectly. static SKScene from .sks

Here is code where I load scene.

func addField(_ hitResult: ARHitTestResult, _ grid: Grid) {
        let gameScene = SKScene(fileNamed: "Scene") // Static .sks (OK)
        //  let gameScene = GameScene(size: CGSize(width: 2560, height: 2560)) //  Custom SKScene (Nope)
        //  gameScene.anchorPoint = CGPoint(x: 0.5, y: 0.5) // Custom SKScene (Nope)
        //  gameScene.scaleMode = .aspectFit // Custom SKScene (Nope)


        let plane = SCNPlane(width: 0.5, height: 0.5)
        plane.firstMaterial?.diffuse.contents = gameScene
        plane.firstMaterial?.isDoubleSided = true

        let paintingNode = SCNNode(geometry: plane)
        paintingNode.transform = SCNMatrix4(hitResult.anchor!.transform)
        paintingNode.eulerAngles = SCNVector3(paintingNode.eulerAngles.x + (-Float.pi / 2), paintingNode.eulerAngles.y, paintingNode.eulerAngles.z)
        paintingNode.position = SCNVector3(hitResult.worldTransform.columns.3.x, hitResult.worldTransform.columns.3.y, hitResult.worldTransform.columns.3.z)

        sceneView.scene.rootNode.addChildNode(paintingNode)
        grid.removeFromParentNode()
    }

So I don't understand why my GameScene is not showing. May be problem is in CGSize, I tried to change it to view.bounds.size but didn't help. I just don't know what else I can place here. If you need more code, just ask. Thanks!

Update: I tried to attach custom class to sks file but it isn't launching, so no effect.


Solution

  • SOLUTION: didMove is not launching in AR, so you need manually attach your SKScene to parent Node.