Search code examples
iosswiftaugmented-realityarkit

Get distance to surface with ARKit


I've begun experimenting with ARKit, and I have ran into an issue. I can't find a tutorial which shows how to place an object on the nearest surface.

Let's say I am using a .scn file that contains a flat object. I know how to place that where the camera is, but how would I get the distance to the nearest surface.

Such as in this image, where it detects how far away the table is.

Sorry if this sounds like a code-request, but I am not sure where to start, any guidance would be much appreciated


Solution

  • You can use the hitTest that might return you results that contains informations such as distance and transform: https://developer.apple.com/documentation/arkit/arhittestresult

    for result in sceneView.hitTest(CGPoint(x: 0.5, y: 0.5), types: [.existingPlaneUsingExtent, .featurePoint]) {
      print(result.distance, result.worldTransform)
    }