How to place a virtual content near a detected reference object

Hi,

I am new to ARkit and having a question about how to place a virtual content on top a detected reference object?


I read this from the Apple's ARkit dev doc about ARObjectAnchor: "To place virtual 3D content that matches the position or size of the detected object, use the anchor's inherited

transform
property together with the
center
and
extent
of the anchor's
referenceObject
."


For example, in my code I got the following of a ARobjectAnchor for a referenobject.


Anchor transform: float4(-0.005025277, -0.19507483, -0.092598796, 1.0)

Refobj center: float3(1.2099743e-05, 0.036919687, -0.0046209693)

Refobj extent: float3(0.089705944, 0.10785053, 0.09547174)


Could anyone offer some help about how get the top surface of the detected object in my code? Thanks.


- Hui

Replies

This will be dependent on a couple of factors:


1. The defined origin for your reference object

2. The defined origin of the model you are placing on top of your reference object


Assuming that you used the default origin location in the ARKit Scanner app (centered on the bottom face of the bounding box), and that the origin of your model is at the very center of the model, then your placement code would look something like this:


func renderer(_ renderer: SCNSceneRenderer, nodeFor anchor: ARAnchor) -> SCNNode? {
        let node = SCNNode()
       
        if let objectAnchor = anchor as? ARObjectAnchor {
            let boxDimension: CGFloat = 0.05
            let model = SCNNode(geometry: SCNBox(width: boxDimension, height: boxDimension, length: boxDimension, chamferRadius: 0))
            // adding boxDimension/2 because SCNBox's origin is at the center of the model
            // adding extent.y because the object's defined origin when scanned was on the bottom face
            model.simdPosition.y = objectAnchor.referenceObject.extent.y + Float(boxDimension/2)
            node.addChildNode(model)
        }
    
        return node
    }

Please pay extra attention to the comments in that snippet. It will not always be the case that your origins are positioned/aligned the same way that this snippet has described!