2

I am learning ARKit and trying to place an object on a detected plane. But it doesn't work properly and there's a space between the plane and the 3D object.

here's my code for the plane detection :

func renderer(_ renderer: SCNSceneRenderer, didAdd node: SCNNode, for anchor: ARAnchor) {
        position = SCNVector3Make(anchor.transform.columns.3.x, anchor.transform.columns.3.y, anchor.transform.columns.3.z)

        guard let planeAnchor = anchor as? ARPlaneAnchor else { return }

        let plane = SCNPlane(width: CGFloat(planeAnchor.extent.x), height: CGFloat(planeAnchor.extent.z))

        planeNode = SCNNode(geometry: plane)
        planeNode.position = position
        planeNode.transform = SCNMatrix4MakeRotation(-Float.pi / 2.0, 1.0, 0.0, 0.0)
        node.addChildNode(planeNode)
}

And then the 3d model gets the same position :

object.position = position

But when I run the application there's a big space between the object and the plane. I didn't figure out why ?

Vasilii Muravev
  • 3,063
  • 17
  • 45
Sam
  • 57
  • 1
  • 7

1 Answers1

1

Because of anchor transform is related to world coordinates. Node in func renderer(_ renderer: SCNSceneRenderer, didAdd node: SCNNode, for anchor: ARAnchor) already positioned in world coordinates. So all that you need - is just add you own node as child node for rendered node:

    func renderer(_ renderer: SCNSceneRenderer, didAdd node: SCNNode, for anchor: ARAnchor) {
        guard let planeAnchor = anchor as? ARPlaneAnchor else { return }

        let plane = SCNPlane(width: CGFloat(planeAnchor.extent.x), height: CGFloat(planeAnchor.extent.z))

        planeNode = SCNNode(geometry: plane)
        planeNode.position = SCNVector3Zero // Position of `planeNode`, related to `node`
        planeNode.transform = SCNMatrix4MakeRotation(-Float.pi / 2.0, 1.0, 0.0, 0.0)
        node.addChildNode(planeNode)
    }
Vasilii Muravev
  • 3,063
  • 17
  • 45
  • Use SCNSphere geometry with 10cm radius and red color for first material to place test nodes, it'll be easier for you to place it correctly. Then, after you'll debug it, you can use any other objects you need. – Vasilii Muravev Aug 10 '17 at 14:58
  • + for pointing out that I must add my object to the rendered node – Mohamed Salah May 15 '20 at 21:13