Now that we have imported the model into our project, let's add it to our scene using code, as follows:
- Create a new file by right-clicking on the ARPortal folder and selecting New Fileā¦, as follows:
- Select Swift File and click Next:
-
Call it Portal.swift and click Create. This will be the class where we will create our full portal, including the 3D model we imported previously.
-
Delete the code and add the ARKit library:
import ARKit
- Create a class:
class Portal: SCNNode {
}
Our portal will be of the SCNNode type.
- Now, inside the class, we'll create a new method to load the 3D model. Add the following code:
func add3DModel() {
let modelScene = SCNScene(named: "vangogh_room.obj")!
let modelNode: SCNNode = modelScene.rootNode.childNodes[0]
self.addChildNode(modelNode)
}
Here, we load the scene from the .obj file and take the node out of it. Then, we attach the node as a child of our portal.
- Now, override the init method, as follows:
override init() {
super.init()
add3DModel()
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
In the first method, we initialize our portal by adding the 3D model. The second method is required for a subclass of SCNNode.
Now that we have added our 3D model, we want to show it in our scene.
We could just open ViewController.swift and add the following at the end of the viewDidLoad() method, as follows:
portal = Portal()
self.sceneView.scene.rootNode.addChildNode(portal!)
The viewDidLoad method will now look as follows:
In this case, the 3D model will appear like the ship we saw at the beginning of this chapter, from the start of the session and in the middle of the screen (we would have to translate it downward for a better view). However, we want to add a twist and attach it to one of the plane anchors when the user taps on the screen, so delete those two lines. We'll learn how to do this in the next section.