2

I am working on a AR project using ARKit.

If I touch only the imported 3D object on a point, I want to place another 3D object above it. (For example I have placed a table above which I have to place something else like a flower vase on the touched point).

How can I solve the problem that the second object should only be placed, when I touch the first 3D object?

The surface of the object is not flat, so I can not use hittest with bounding box.

Informatics
  • 155
  • 1
  • 10

1 Answers1

1

One approach is to give the first imported 3D object a node name.

 firstNode.name = “firstObject”

Inside you tapped gesture function you can do a hitTest like this

 let tappedNode = self.sceneView.hitTest(location, options: [:])

  let node = tappedNode[0].node

 if node.name == “firstObject” {

    let height = firstNode.boundingBox.max.y -firstNode.boundingBox.min.y


   let position2ndNode = SCNVector3Make(firstNode.worldPosition.x, (firstNode.worldPosition.y + height), firstNode.worldPosition.z)


  2ndNode.position = position2ndNode

sceneView.scene.rootNode.addChildNode(2ndNode)

 } else {
      return
 }

This way when you tap anywhere else the 2nd object won’t get placed. It will only place when you tap on the node itself. It doesn’t matter where you tap on the node, because we only want the height & we can determine that from its boundingBox max - min which we then add to the firstnode.worldPosition.y

Make sure you set at the top of ARSCNView class

 var firstNode = SCNNode! 

this way we can access the firstNode in the tap gesture function.

Edit: If the first 3D model has many nodes. You can flattenNode on the parent Node in the sceneGraph (best illustrated with photo below). This removes all the childNodes and wraps from the sceneGraph. You can then just work with the parentNode.

enter image description here

Clay
  • 1,721
  • 2
  • 10
  • 18
  • Thanks a lot! I have a question about the bounding box. My first object has multiple nodes. After adding every node as childnode, should I do the if-else-condition for every node? – Informatics Feb 05 '18 at 15:20
  • I updated the answer about how flattenNode (remove all the childNodes) leaving just the parentNode. Let me know if that fixes your problem. If not I may have another way to fix the boundingBox issue. Note: If xcode crashes when you do it on a dae... convert the dae file to scn file first. It will work then. – Clay Feb 05 '18 at 19:28