UNPKG

@react-three/xr

Version:

VR/AR for react-three-fiber

48 lines (47 loc) 2.17 kB
import { jsx as _jsx, Fragment as _Fragment } from "react/jsx-runtime"; import { isFacingCamera } from '@pmndrs/xr'; import { useFrame, useThree } from '@react-three/fiber'; import { useRef, useState } from 'react'; function useIsFacingCamera(ref, set, direction, angle) { const camera = useThree((state) => state.camera); useFrame(() => { if (ref.current == null) { return; } set(isFacingCamera(camera, ref.current, direction, angle)); }); } /** * Guard that only **shows** its children by toggling their visibility if the camera is facing the object. * Calculation is based on the provided angle and direction. * * @param props * #### `children` - `ReactNode` The ReactNode elements to conditionally show. * #### `direction` - [Vector3](https://threejs.org/docs/#api/en/math/Vector3) Direction vector to check against the camera's facing direction. * #### `angle` - `number` The angle in radians to determine visibility. Defaults to `Math.PI / 2` (90 degrees). */ export function ShowIfFacingCamera({ children, direction, angle = Math.PI / 2 }) { const ref = useRef(null); useIsFacingCamera(ref, (visible) => { if (ref.current == null) { return; } ref.current.visible = visible; }, direction, angle); return _jsx("group", { ref: ref, children: children }); } /** * Guard that only **renders** its children into the scene if the camera is facing the object. * Calculation is based on the provided angle and direction. * * @param props * #### `children` - `ReactNode` The ReactNode elements to conditionally render. * #### `direction` - [Vector3](https://threejs.org/docs/#api/en/math/Vector3) Direction vector to check against the camera's facing direction. * #### `angle` - `number` The angle in radians to determine visibility. Defaults to `Math.PI / 2` (90 degrees). */ export function IfFacingCamera({ children, direction, angle = Math.PI / 2 }) { const ref = useRef(null); const [show, setShow] = useState(false); useIsFacingCamera(ref, setShow, direction, angle); return show ? _jsx(_Fragment, { children: children }) : null; }