raycast-manager.md 4.19 KB
uid: arfoundation-raycast-manager

AR Raycast Manager

The ARRaycastManager is a type of trackable manager.

AR Raycast Manager

Ray casting

Also known as hit testing, ray casting allows you to determine where a ray (defined by an origin and direction) intersects with a trackable. The current ray cast interface only tests against planes and points in the point cloud. The ray cast interface is similar to the one in the Unity Physics module, but since AR trackables don't necessarily have a presence in the physics world, AR Foundation provides a separate interface.

The raycast manager serves two purposes:

  1. Provides an API to perform single raycasts.
  2. Allows you to create a persistent ARRaycast. An ARRaycast is a type of trackable and is updated automatically until you remove it. Conceptually, it is similar to repeating the same raycast query each frame, but platforms with direct support for this feature can provide better results.

Single raycasts

There are two ray casting methods on the ARRaycastManager that perform single raycasts.

The first method takes a two-dimensional pixel position on the screen.

[!code-csARRaycastManager_Raycast_screenPoint]

You can, for example, pass a touch position directly:

[!code-csraycast_using_touch]

The second method takes an arbitrary Ray (a position and direction):

[!code-csARRaycastManager_Raycast_ray]

The following table summarizes the other parameters:

| Parameter | Description | |:- |:-| | hitResults | The results for both methods are stored in this List, which must not be null. This lets you reuse the same List object to avoid garbage-collected allocations. | | trackableTypeMask | The type(s) of trackable(s) to hit test against. This is a flag, so multiple types can be bitwise OR'd together, for example, TrackableType.PlaneWithinPolygon | TrackableType.FeaturePoint |

Determining what the raycast hit

If the raycast hits something, hitResults will be populated with a List of ARRaycastHits.

Use the hitType to determine what kind of thing the raycast hit. If it hit a trackable, e.g., a plane, then the ARRaycastHit.trackable property can be cast to that type of trackable:

[!code-csraycasthit_trackable]

Persistent raycasts

Persistent raycasts are a type of trackable. Each ARRaycast continues to update automatically until you remove it or disable the ARRaycastManager.

To add or remove a persistent raycast, call AddRaycast or RemoveRaycast on the ARRaycastManager component from script code.

Persistent raycasts must be created from a screen point:

[!code-csARRaycastManager_AddRaycast_screenPoint]

When you create a new ARRaycast, ARFoundation creates a new GameObject with an ARRaycast component on it. You can optionally provide a prefab in the "Raycast Prefab" field that will be instantiated for each ARRaycast, which allows you to extend the default behavior of each ARRaycast.