1

我正在尝试将drei Html元素固定到左上角。我正在努力让它在旋转或移动相机时保持在同一位置。这是我目前的尝试:

  const { mouse2D, mouse3D, normal, plane } = useMemo(() => {
    return {
      mouse2D: new THREE.Vector2(),
      mouse3D: new THREE.Vector3(),
      normal: new THREE.Vector3(),
      plane: new THREE.Plane(),
    };
  }, []);

  const { width, height } = useWindowDimensions();

  useFrame(({camera, raycaster, size}) => {
    mouse2D.set(((0.02 * width) / size.width) * 2 - 1, ((-0.02 * height) / size.height) * 2 + 1);
    raycaster.setFromCamera(mouse2D, camera);
    camera.getWorldDirection(normal).negate();
    plane.setFromNormalAndCoplanarPoint(normal, mouse3D);
    raycaster.ray.intersectPlane(plane, mouse3D);
  });

  return <Html position={[mouse3D.x, mouse3D.y, mouse3D.z]}>stuff</Html>;

Html 位置在窗口调整大小时正确更新,但在相机旋转或相机移动时不会更新。有人知道如何解决这个问题吗?

4

1 回答 1

0

如果有人感兴趣,这是我目前的解决方案:

const { viewport } = useThree();

const groupRef = useRef<THREE.Group>(null!);
  useEffect(() => {
    const groupRefCopy = groupRef.current;
    camera.add(groupRefCopy);
    return () => {
      camera.remove(groupRefCopy);
    };
  }, [camera, groupRef.current]);

  return (
    <group ref={groupRef} position={[-viewport.width / 3.5, viewport.height / 3.8, -5]} rotation={[0, 0, 0]}>
      <Html style={{ opacity: show ? 1 : 0, width: menuWidth, userSelect: "none", pointerEvents: show? "auto" : "none" }}>
         {...}
      </Html>
    </group>
  );

3.5 和 3.8 非常适合我的场景。如果有人知道如何从 3JS 动态获取这些常量,请发表评论!

于 2021-09-13T08:47:06.777 回答