简体   繁体   中英

ARKit - getting distance from camera to anchor

I'm creating an anchor and adding it to my ARSKView at a certain distance in front of the camera like this:

func displayToken(distance: Float) {
        print("token dropped at: \(distance)")
        guard let sceneView = self.view as? ARSKView else {
            return
        }

        // Create anchor using the camera's current position
        if let currentFrame = sceneView.session.currentFrame {
            // Create a transform with a translation of x meters in front of the camera
            var translation = matrix_identity_float4x4
            translation.columns.3.z = -distance
            let transform = simd_mul(currentFrame.camera.transform, translation)

            // Add a new anchor to the session
            let anchor = ARAnchor(transform: transform)
            sceneView.session.add(anchor: anchor)
        }
    }

then the node gets created for the anchor like this:

func view(_ view: ARSKView, nodeFor anchor: ARAnchor) -> SKNode? {
        // Create and configure a node for the anchor added to the view's session.
        if let image = tokenImage {
            let texture = SKTexture(image: image)
            let tokenImageNode = SKSpriteNode(texture: texture)
            tokenImageNode.name = "token"
            return tokenImageNode
        } else {
            return nil
        }
    }

This works fine and I see the image get added at the appropriate distance. However, what I'm trying to do is then calculate how far the anchor/node is in front of the camera as you move. The problem is the calculation seems to be off immediately using fabs(cameraZ - anchor.transform.columns.3.z). Please see my code below that is in the update() method to calculate distance between camera and object:

override func update(_ currentTime: TimeInterval) {
        // Called before each frame is rendered
        guard let sceneView = self.view as? ARSKView else {
            return
        }

        if let currentFrame = sceneView.session.currentFrame {
            let cameraZ =  currentFrame.camera.transform.columns.3.z
            for anchor in currentFrame.anchors {
                if let spriteNode = sceneView.node(for: anchor), spriteNode.name == "token", intersects(spriteNode) {
                    // token is within the camera view
                    //print("token is within camera view from update method")
                    print("DISTANCE BETWEEN CAMERA AND TOKEN: \(fabs(cameraZ - anchor.transform.columns.3.z))")
                    print(cameraZ)
                    print(anchor.transform.columns.3.z)
                }
            }
        }
    }

Any help is appreciated in order to accurately get distance between camera and the anchor.

The last column of a 4x4 transform matrix is the translation vector (or position relative to a parent coordinate space), so you can get the distance in three dimensions between two transforms by simply subtracting those vectors.

let anchorPosition = anchor.transforms.columns.3
let cameraPosition = camera.transform.columns.3

// here’s a line connecting the two points, which might be useful for other things
let cameraToAnchor = cameraPosition - anchorPosition
// and here’s just the scalar distance
let distance = length(cameraToAnchor)

What you're doing isn't working right because you're subtracting the z-coordinates of each vector. If the two points are different in x, y, and z, just subtracting z doesn't get you distance.

This one is for scenekit, I'll leave it here though.

let end = node.presentation.worldPosition
let start = sceneView.pointOfView?.worldPosition

let dx = (end?.x)! - (start?.x)!
let dy = (end?.y)! - (start?.y)!
let dz = (end?.z)! - (start?.z)!

let distance = sqrt(pow(dx,2)+pow(dy,2)+pow(dz,2))

With RealityKit there is a slightly different way to do this. If you're using the world tracking configuration, your AnchorEntity object conforms to HasAnchoring which gives you a target . Target is an enum of AnchoringComponent.Target . It has a case .world(let transform) . You can compare your world transform to the camera's world transform like this:

if case let AnchoringComponent.Target.world(transform) = yourAnchorEntity.anchoring.target {
    let theDistance = distance(transform.columns.3, frame.camera.transform.columns.3)
 }

This took me a bit to figure out but I figure others that might be using RealityKit might benefit from this.

正如@codeman 上面提到的,这是正确的解决方案:

let distance = simd_distance(YOUR_NODE.simdTransform.columns.3, (sceneView.session.currentFrame?.camera.transform.columns.3)!);

3D distance - You can check these utils,

class ARSceneUtils {
        /// return the distance between anchor and camera.
        class func distanceBetween(anchor : ARAnchor,AndCamera camera: ARCamera) -> CGFloat {
        let anchorPostion = SCNVector3Make(
            anchor.transform.columns.3.x,
            anchor.transform.columns.3.y,
            anchor.transform.columns.3.z
        )
        let cametaPosition = SCNVector3Make(
            camera.transform.columns.3.x,
            camera.transform.columns.3.y,
            camera.transform.columns.3.z
        )
        return CGFloat(self.calculateDistance(from: cametaPosition , to: anchorPostion))
    }

    /// return the distance between 2 vectors.
    class func calculateDistance(from: SCNVector3, to: SCNVector3) -> Float {
        let x = from.x - to.x
        let y = from.y - to.y
        let z = from.z - to.z
        return sqrtf( (x * x) + (y * y) + (z * z))
    }

}

And now you can call:

guard let camera = session.currentFrame?.camera else { return }
let anchor = // you anchor
let distanceAchorAndCamera = ARSceneUtils.distanceBetween(anchor: anchor, AndCamera: camera)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM