useXRHitTestSource

useXRHitTestSource(relativeTo, trackableType?): undefined | { getWorldMatrix: (...args) => boolean; source: XRHitTestSource; }

Hook for creating a hit test source originating from the provided object or XRSpace. The provided object must be statically positioned in the XRSpace.

Parameters

relativeTo

The XRSpace, XRReferenceSpace, or Object3D to perform hit-tests from

XRSpace | XRReferenceSpaceType | RefObject<null | Object3D<Object3DEventMap>>

trackableType?

A string, or array of strings that specify the types of surfaces to hit test against ('point', 'plane', 'mesh')

XRHitTestTrackableType | XRHitTestTrackableType[]

Returns


undefined | { getWorldMatrix: (...args) => boolean; source: XRHitTestSource; }

Example

function ManualHitTest() {
  const meshRef = useRef<Mesh>(null)
  const hitTestSource = useXRHitTestSource('viewer')
  const [someCondition, setSomeCondition] = useState(false)
  const [hitResults, setHitResults] = useState<XRHitTestResult[]>([])

  useFrame((_, __, frame: XRFrame | undefined) => {
    // Only perform hit testing when certain conditions are met
    if (frame && hitTestSource && someCondition) {
      const results = frame.getHitTestResults(hitTestSource.source)
      setHitResults(results)
    }
  })
  return (
    <IfInSessionMode allow={'immersive-ar'}>
      <XRDomOverlay>
        <button onClick={() => setSomeCondition(true)}>Turn on hit testing</button>
      </XRDomOverlay>
    </IfInSessionMode>
  )
}

See