Sam
Sam

Reputation: 57

ARKIT : place object on a plane doesn't work properly

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 ?

Upvotes: 2

Views: 1533

Answers (1)

Vasilii Muravev
Vasilii Muravev

Reputation: 3163

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)
    }

Upvotes: 1

Related Questions