Theory
It's a bit tricky in RealityKit 2.0 . The position of the entity relative to its parent is:
public var position: SIMD3<Float>
// the same as: entity.transform.translation
But in your case, it doesn't work for AnchorEntity that has no parent. What actually does work is an instance method that returns a position of an entity relative to referenceEntity
(even if it's nil
, because nil
implies a world space):
public func position(relativeTo referenceEntity: Entity?) -> SIMD3<Float>
Solution
import UIKit
import RealityKit
class ViewController: UIViewController {
@IBOutlet var arView: ARView!
let anchor_01 = AnchorEntity(world: [ 1.22, 1.47,-2.75])
let anchor_02 = AnchorEntity(world: [-2.89, 0.15, 1.46])
override func viewDidLoad() {
super.viewDidLoad()
arView.scene.anchors.append(anchor_01)
arView.scene.anchors.append(anchor_02)
let dst = distanceBetweenEntities(anchor_01.position(relativeTo: nil),
and: anchor_02.position(relativeTo: nil))
print("The distance is: \(dst)") // WORKS
print("The position is: \(anchor_01.position)") // doesn't work
}
private func distanceBetweenEntities(_ a: SIMD3<Float>,
and b: SIMD3<Float>) -> SIMD3<Float> {
var distance: SIMD3<Float> = [0, 0, 0]
distance.x = abs(a.x - b.x)
distance.y = abs(a.y - b.y)
distance.z = abs(a.z - b.z)
return distance
}
}
Result:
// The distance is: SIMD3<Float>(4.11, 1.32, 4.21)
// The position is: SIMD3<Float>(0.0, 0.0, 0.0)