Interaction

Added in 1.0.0-alpha09

public final class Interaction


Summary

Public methods

static final @NonNull List<@NonNull HitResult>
hitTest(@NonNull Session session, @NonNull Ray ray)

Performs a hit-test using the given ray.

Public methods

public static final @NonNull List<@NonNull HitResulthitTest(@NonNull Session session, @NonNull Ray ray)

Performs a hit-test using the given ray.

A hit-test is a method of calculating the intersection of a ray with objects tracked by the session. Conducting a hit-test results in a list of hit objects, in other words, a hit-test does not stop at the first object hit.

import androidx.xr.arcore.Anchor
import androidx.xr.arcore.ArDevice
import androidx.xr.arcore.Plane
import androidx.xr.arcore.hitTest
import androidx.xr.runtime.math.Pose
import androidx.xr.runtime.math.Ray
import androidx.xr.scenecore.scene

val arDevice = ArDevice.getInstance(session)

// Assume hitOrigin and hitDirection are in Activity Space.
// We need to transform the ray into Perception Space for hitTest.

// Transform the origin point from Activity Space to Perception Space.
val perceptionOrigin =
    session.scene.activitySpace
        .transformPoseTo(Pose(hitOrigin), session.scene.perceptionSpace)
        .translation

// Transform the direction vector from Activity Space to Perception Space.
val perceptionDirection =
    session.scene.activitySpace
        .transformPoseTo(Pose(hitDirection), session.scene.perceptionSpace)
        .translation
        .toNormalized() // Ensure the direction is normalized after transformation.

val ray = Ray(perceptionOrigin, perceptionDirection)

hitTest(session, ray)
    // Use a valid plane label as a test to filter out any unreliable hits.
    .firstOrNull { (it.trackable as? Plane?)?.state?.value?.label != Plane.Label.UNKNOWN }
    ?.let { hitResult ->
        // Do something with the hit result, like create an anchor representing where the ray
        // intersected the plane. The hitResult.hitPose is in Perception Space.
        val anchorResult = Anchor.create(session, hitResult.hitPose)

        // Anchor creation can fail, so it is important to properly handle the return value of
        // and `Anchor.create()` call. See `Anchor.create()` for more information.
        yourAnchorResultHandler(anchorResult)

        // If rendering is needed, transform hitResult.hitPose from Perception Space
        // to the desired Scene Space (e.g., Activity Space).
        val activitySpaceHitPose =
            session.scene.perceptionSpace.transformPoseTo(
                hitResult.hitPose,
                session.scene.activitySpace,
            )
        renderSomething(activitySpaceHitPose)
    }
Returns
@NonNull List<@NonNull HitResult>

A list of HitResult objects, sorted by distance from the origin of the ray. The nearest hit is at the beginning of the list.