Single ray casts
Single ray casts occur once. Use single ray casts for discrete, one time user interactions with the environment. For example, placement of a virtual object on a detected surface to preview what it looks like in a user's room.
There are two Raycast
methods on the ARRaycastManager that perform single ray casts. Refer to Optional feature platform support to check whether your target platform supports each type of ray casting method.
Method | Description |
---|---|
Viewport based ray cast | Casts a ray from a two-dimensional pixel position on the screen (a screen point). |
World based ray cast | Casts an arbitrary ray (a position and direction). |
Viewport based ray cast
The viewport based Raycast method casts a ray from a two-dimensional pixel position on the screen:
public bool Raycast(
Vector2 screenPoint,
List<ARRaycastHit> hitResults,
TrackableType trackableTypes = TrackableType.AllTypes)
You can, for example, pass a touch position directly:
[SerializeField]
ARRaycastManager m_RaycastManager;
List<ARRaycastHit> m_Hits = new List<ARRaycastHit>();
void Update()
{
if (Input.touchCount == 0)
return;
if (m_RaycastManager.Raycast(Input.GetTouch(0).position, m_Hits))
{
// Only returns true if there is at least one hit
}
}
World based ray cast
The world based Raycast method takes an arbitrary Ray (a position and direction):
public bool Raycast(
Ray ray,
List<ARRaycastHit> hitResults,
TrackableType trackableTypes = TrackableType.AllTypes)
Parameters
The following table describes the common parameters of the Raycast
methods:
Parameter | Description |
---|---|
hitResults |
Contents are replaced with the ray cast results, if successful. Results are sorted by distance in closest-first order. |
trackableType |
(Optional) The types of trackables to cast against. |
Determine what the ray cast hit
If the ray cast hits something, hitResults
is populated with a List
of ARRaycastHits.
Use the hitType to determine what kind of thing the ray cast hit. If it hit a trackable, such as a plane, then the ARRaycastHit.trackable property can be cast to that type of trackable:
void HandleRaycast(ARRaycastHit hit)
{
if (hit.trackable is ARPlane plane)
{
// Do something with 'plane':
Debug.Log($"Hit a plane with alignment {plane.alignment}");
}
else
{
// What type of thing did we hit?
Debug.Log($"Raycast hit a {hit.hitType}");
}
}