'How can I calculate a distance between two AnchorEntities?

There's a position which is SIMD3 and there's AnchorEntity. I want to get distance between two.

How I did it:

var distance = distance(position, (self.modelentity.position(relativeTo:nil))
var distance = distance(position, (self.modelentity.position)

But both failed because it seems calculating distance between world origin anchor not distance between position to self.modelentity.

How can I calculate distance?



Solution 1:[1]

Theory

It's a little 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)

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1