【问题标题】:Use the same GLTF model twice in react-three-fiber/drei/Three.js在 react-three-fiber/drei/Three.js 中两次使用相同的 GLTF 模型
【发布时间】:2021-10-19 03:34:21
【问题描述】:

在这个最小的 react-three-fiber 应用程序中,我尝试加载并包含相同的 GLTF 模型两次:

import React, { Suspense } from "react";
import { Canvas } from "@react-three/fiber";
import { useGLTF } from "@react-three/drei";

function MyContent() {
  const firstGltf = useGLTF("/eye/scene.gltf");
  const secondGltf = useGLTF("/eye/scene.gltf");

  return (
    <>
      <primitive object={firstGltf.scene} position={[-200, 0, -400]} />
      <primitive object={secondGltf.scene} position={[200, 0, -400]} />
    </>
  );
}

export default function App() {
  return (
    <Canvas>
      <ambientLight color="white" intensity={0.5} />

      <Suspense fallback={null}>
        <MyContent />
      </Suspense>
    </Canvas>
  );
}

看到这个codesandbox

但是只有第二个&lt;primitive&gt; 是可见的。如果我删除第二个&lt;primitive&gt;,则第一个可见。 我很难理解为什么会发生这种情况以及如何做得更好。

(是因为第二次调用useGLTF 记得"/eye/scene.gltf" 已经加载并返回相同的对象吗?这是否以某种方式混淆了&lt;primitive&gt; 的使用,可能是因为材料/几何形状还没有被重新创建了第二次并且只存在一次?)

特别是,这是我想要实现的:

  • 在我的画布上多次使用 gltf 模型
  • 理想情况下,只加载一次 gltf

最重要的是,也许您也可以帮助我澄清这些问题,以便我更好地了解这里实际发生的情况:

  • 既然我只想要一个 3D 模型,那么使用 gltf.scene 对象的方法是否正确?
  • &lt;primitive&gt; 实际上是显示 3D 模型的正确方法吗?或者我应该以某种方式从场景中提取几何/纹理并进行渲染?

谢谢!

【问题讨论】:

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


    【解决方案1】:

    我不是three.js 方面的专家,仅根据我的发现并尝试回答您的问题。


    1.即使定义了 2 个图元,也只显示一只眼睛

    如果您使用useGLTF() 导入相同的模型,它将引用相同的对象。因此,这 2 个原语指向同一个 gltf,并且只应用了最后一个/一个配置。

    const firstGltf = useGLTF("/eye/scene.gltf");
    const secondGltf = useGLTF("/eye/scene.gltf");
    const glassesGltf = useGLTF("/glasses/scene.gltf");
    
    // for demonstrating first eye is same as second eye
    // Output: false, true
    console.log(firstGltf === glassesGltf, firstGltf === secondGltf);
    

    2。 &lt;primitive&gt; 真的是展示 3D 模型的正确方法吗?

    是的,是的。但如果您想在屏幕上多次显示相同的 gltf,则需要创建网格并应用模型的几何形状和材质,这样您就可以拥有一个新对象。

    function Model(props) {
      const { nodes, materials } = useGLTF("/eye/scene.gltf");
      return (
        <group
          {...props}
          dispose={null}
          rotation={[Math.PI, 0, -Math.PI / 2]}
          scale={[1, 1, 1]}
        >
          <mesh
            geometry={nodes.Sphere001_Eye_0.geometry}
            material={materials.material}
          />
        </group>
      );
    }
    ...
    <Model position={[-1, 0, 1]} />
    <Model position={[1, 0, 1]} />
    

    这里是codesandbox for demo


    财政年度:

    你可以使用这个库https://github.com/pmndrs/gltfjsx从模型生成jsx。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-12-23
      • 2022-01-25
      • 1970-01-01
      • 2021-12-08
      • 2021-07-02
      • 1970-01-01
      • 1970-01-01
      • 2020-11-26
      相关资源
      最近更新 更多