useXRHitTest

useXRHitTest(fn, relativeTo, trackableType?): void

Hook for setting up a continous hit test originating from the provided object or XRSpace. The provided object must be statically positioned in the XRSpace.

Parameters

fn

Callback function that contains the results of the hit test, and a function to retrieve the world matrix

undefined | (results, getWorldMatrix) => void

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


void

Example

const matrixHelper = new Matrix4()
const hitTestPosition = new Vector3()

function ContinuousHitTest() {
  const previewRef = useRef<Mesh>(null)

  useXRHitTest(
    (results, getWorldMatrix) => {
      if (results.length === 0) return

      getWorldMatrix(matrixHelper, results[0])
      hitTestPosition.setFromMatrixPosition(matrixHelper)
    },
    'viewer'
  )

  useFrame(() => {
    if (hitTestPosition && previewRef.current) {
      previewRef.current.position.copy(hitTestPosition)
    }
  })

  return (
      <mesh ref={previewRef} position={hitPosition}>
        <sphereGeometry args={[0.05]} />
        <meshBasicMaterial color="red" />
      </mesh>
  )
}

See