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

Time:05-14

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?

CodePudding user response:

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