Search code examples
iosswiftobjectaugmented-realityarkit

ARKit drop a custom object in the scene


I'm playing with the new ARKit and I was able to create a new file called SphereNode that is able to create a Sphere droppable on the view.

The point is that I really want to add a custom object instead of the standard sphere. Some suggestions? Here you are the code used for create the Sphere:

import SceneKit

class SphereNode: SCNNode {
    init(position: SCNVector3) {
        super.init()
        let sphereGeometry = SCNSphere(radius: 0.005)
        let material = SCNMaterial()
        material.diffuse.contents = UIColor.red
        material.lightingModel = .physicallyBased
        sphereGeometry.materials = [material]
        self.geometry = sphereGeometry
        self.position = position
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
}

Solution

  • To use a custom geometry instead of the provided ones your best bet is to use an external editor to create your scene, such as Blender which also open source, optionally add materials and textures and then export it to a format that iOS can use, such as DAE. Inside your app you can then load this file and obtain a SCNScene with its appropriate initializer. Once you have loaded the scene you can directly use it to display to the user or navigate it to obtain only the node/geometry/material you want to use then as you please such as add it to an already existing scene.

    1. Let’s say your file is called scene.dae and located in your app main bundle then you can load it as

      let scene = SCNScene(named: “scene.dae”)
      

      or if you prefer you can also specify a full URL, refer to the documentation for further details, note that these are failable initializer so check for nil.

    2. Let’s say your node with its custom geometry and texture is the only object in the scene, you can then obtain a reference to it with

      let obj = scene.rootNode.childNodes.first
      

      Note that this is also an optional so check for nil values, if my assumptions are not correct you can refer to SCNNode documentation for how to navigate the node graph, scene.rootNode is always your starting point.

    3. Now that you have your scene and object as I previously said you have two choice: link the scene directly to your SCNView (I don’t know ARKit but I guess you have one) instead of manually creating an empty one, or take only the object/geometry/material and normally add it to your already created scene.

    If your object is not static but generated dynamically you can also create it point by point by building a SCNGeometry, doing this is a bit tricky, you could use my library as I created some helpful function and classes to aid the process.