【问题标题】:react three fiber lock object position in canvas在画布中反应三个纤维锁定对象位置
【发布时间】:2021-10-18 03:15:00
【问题描述】:

我是 Threejs 和 react-three-fiber 的新手。当透视相机旋转和移动时,如何锁定画布中的对象(锁定位置、旋转)。我想制作一个避免透视相机移动并保持固定位置的对象

【问题讨论】:

    标签: reactjs three.js react-three-fiber


    【解决方案1】:

    您可以use refs to access underlying objects,从而修改它们的位置、旋转等。

    由于PerspectiveCameraObject3D,您可以将此网格添加为子网格,以便它们一起移动。

    import { useRef } from 'react';
    import { useThree } from '@react-three/fiber';
    
    const MyMesh = () => {
      const { camera } = useThree();
      const ref = useRef();
    
      useEffect(() => {
        // Add mesh to camera
        const meshRef = ref.current;
        camera.add(meshRef);
    
        // Cleanup on unmount
        return () => {
          camera.remove(meshRef);
        };
      }, [camera, ref.current]);
    
      return <mesh ref={ref} position={[0, 0, -5]} />;
    };
    

    在这里,我通过 useThree 钩子通过其上下文访问 Fiber 的摄像头。

    或者,您可以在每一帧复制相机的属性并应用偏移量。这将导致相同的显示行为。

    您可以通过useFrame 挂钩访问渲染循环。这在三个内部运行,因此在 React 中没有开销。值得注意的是,您也可以从钩子的回调中访问 Fiber 的上下文。

    import { useRef } from 'react';
    import { useFrame } from '@react-three/fiber';
    
    const MyMesh = () => {
      const ref = useRef();
    
      useFrame(({ camera }) => {
        // Move mesh to be flush with camera
        ref.current.position.copy(camera.position);
        ref.current.quaternion.copy(camera.quaternion);
    
        // Apply offset
        ref.current.translateZ(-5);
      });
    
      return <mesh ref={ref} />;
    };
    

    【讨论】:

      猜你喜欢
      • 2021-07-10
      • 2021-10-16
      • 2021-12-15
      • 2021-08-18
      • 2022-12-23
      • 2021-08-01
      • 1970-01-01
      • 1970-01-01
      • 2021-04-18
      相关资源
      最近更新 更多