How to measure distance using ARCore?

Alexey Podolian picture Alexey Podolian · Aug 31, 2017 · Viewed 13.2k times · Source

Is it possible to calculate distance between two HitResult `s ?

Or how we can calculate real distance (e.g. meters) using ARCore?

Answer

Ian M picture Ian M · Aug 31, 2017

In Java ARCore world units are meters (I just realized we might not document this... aaaand looks like nope. Oops, bug filed). By subtracting the translation component of two Poses you can get the distance between them. Your code would look something like this:

On first hit as hitResult:

startAnchor = session.addAnchor(hitResult.getHitPose());

On second hit as hitResult:

Pose startPose = startAnchor.getPose();
Pose endPose = hitResult.getHitPose();

// Clean up the anchor
session.removeAnchors(Collections.singleton(startAnchor));
startAnchor = null;

// Compute the difference vector between the two hit locations.
float dx = startPose.tx() - endPose.tx();
float dy = startPose.ty() - endPose.ty();
float dz = startPose.tz() - endPose.tz();

// Compute the straight-line distance.
float distanceMeters = (float) Math.sqrt(dx*dx + dy*dy + dz*dz);

Assuming that these hit results don't happen on the same frame, creating an Anchor is important because the virtual world can be reshaped every time you call Session.update(). By holding that location with an anchor instead of just a Pose, its Pose will update to track the physical feature across those reshapings.