RealityKit – Why AnchorEntity position is always (x: 0, y: 0, z: 0)

Viewed 201

I am using the following to to place an object on a plane. It works but the position of the anchor is always coming out to be 0,0,0 even though it is based on the raycast result.

let results = arView.raycast(from: tappedLocation, 
                         allowing: .estimatedPlane, 
                        alignment: .horizontal)

if let result = results.first {

    print(result.worldTransform)    // contains values 
    let anchor = AnchorEntity(raycastResult: result)
    print(anchor.position)          // why 0,0,0 
}

Any ideas?

2 Answers

It seems that position becomes zero when anchor is nil (transform becomes identity matrix).

If we call raycast with .existingPlaneGeometry, anchor will not be nil.

AnchorEntity has world space position inside. This is not included in transform.

If we want to know world space position, we can calculate it by the following code. (It seems that there is no property that can be obtained...)

let anchorWorldTransform = anchorEntity.convert(transform: .identity, to: nil)

Alternative approach

If .init(raycastResult:) doesn't work, use alternative approach with .init(world:) initializer.

fileprivate func raycaster() {
        
    guard let query = arView.makeRaycastQuery(from: arView.center,
                                          allowing: .existingPlaneInfinite,
                                         alignment: .horizontal)
    else { return }

    if let result = arView.session.raycast(query).first {

        let anchor = AnchorEntity(world: result.worldTransform)
        anchor.addChild(self.yourModel)
        arView.scene.anchors.append(anchor)
    }
}

Then:

override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {

    self.raycaster()
}

Modifying your code

Also, you may modify your code adding these lines:

let anchor = AnchorEntity(raycastResult: result)
let transform = Transform(matrix: result.worldTransform)
anchor.transform = transform
Related