Hit-Testing

Using a screen location, find points on real-world surfaces and objects.

Enabling Hit-Testing

In general, hit-tests can be run against:

  • feature points

  • estimated planes

  • existing planes

See the ARHitTestResultType values for a full enumeration of possible types.

In order to hit-test against existing planes, the ARSession has to be configured to detect planes.

void RunARSession(IARSession arSession)
{
  var config = ARWorldTrackingConfigurationFactory.Create();

  // Set to value other than PlaneDetection.None to enable
  // hit tests against detected planes
  config.PlaneDetection = PlaneDetection.Horizontal;

  arSession.Run(config);
}

Hit-Tests

Use the IARFrame.HitTest method to efficiently check if a given pixel on the screen intersects any real world features.

using Niantic.ARDK.AR.HitTest;

void SpawnAtHitPoint(IARSession arSession, Camera activeCamera, GameObject prefab, float verticalOffset)
{
    // Check if the user's touched the screen
    var touch = PlatformAgnosticInput.GetTouch(0);
    if (touch.phase != TouchPhase.Began)
        return;

    // If the ARSession isn't currently running, its CurrentFrame property will be null
    var currentFrame = arSession.CurrentFrame;
    if (currentFrame == null)
        return;

    // Hit test from the touch position
    var results =
        arSession.CurrentFrame.HitTest
        (
            activeCamera.pixelWidth,
            activeCamera.pixelHeight,
            touch.position,
            ARHitTestResultType.All
        );

    if (results.Count == 0)
        return;

    var closestHit = results[0];
    var position = closestHit.WorldTransform.ToPosition();

    // The position y-value offset needed to spawn your prefab at the
    // correct height (not intersecting with the plane) will depend on
    // where the center of your prefab is.
    position.y += verticalOffset;

    GameObject.Instantiate(prefab, position, Quaternion.identity);
}

Notes:

  • The returned array of ARHitTestResults are in order of closest to furthest.

  • All ARHitTestResultType values excluding ARHitTestResultType.ExistingPlaneUsingExtent are not supported in either Virtual Studio’s Mock or Remote mode.