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 ARRaycast
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 OnEnable()
{
InputSystem.EnhancedTouch.EnhancedTouchSupport.Enable();
}
void OnDisable()
{
InputSystem.EnhancedTouch.EnhancedTouchSupport.Disable();
}
void Update()
{
var activeTouches = InputSystem.EnhancedTouch.Touch.activeTouches;
if (activeTouches.Count == 0)
return;
if (m_RaycastManager.Raycast(activeTouches[0].screenPosition, 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 ARRaycast
Use the hit
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}");
}
}