Adding the model to our scene

Now that we have imported the model into our project, let's add it to our scene using code, as follows:

  1. Create a new file by right-clicking on the ARPortal folder and selecting New Fileā€¦, as follows:

Creating a new file
  1. Select Swift File and click Next:

Selecting Swift File
  1. 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.

  2. Delete the code and add the ARKit library:

import ARKit
  1. Create a class:
class Portal: SCNNode {
}

Our portal will be of the SCNNode type.

  1. 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.

If you use another model and it doesn't appear where you want it to be (displaced in one or more axes), you can adjust its position inside this method by adding the following before the self.addChildNode(modelNode) line: modelNode.position = SCNVector3(x: YourValue, y: YourValue, z: YourValue). You can check how coordinates work in SceneKit by looking at the diagram at the beginning of this section.
  1. 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:

The viewDidLoad method with the Portal added

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.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.17.75.227