【问题标题】:Change material of gltf-imported mesh programmatically - react three fiber以编程方式更改 gltf 导入网格的材料 - 反应三纤维
【发布时间】:2021-11-11 03:34:16
【问题描述】:

我目前正在使用 react-three-fiber 进行一个项目。我已经从 @react-three/drei 导入了带有 useGLTF 的模型。

const { nodes, materials } = useGLTF('/model.glb');

我从 glb 文件访问材料。 为了访问和操作模型,我使用 gltfjsx 生成模型。

现在我需要以编程方式更改网格的材质。因为我无法直接访问模型的 JSX,所以我使用 React.cloneElement 进行操作并修改网格的道具。

所以我尝试了这样的事情:

return React.cloneElement(mesh, {
  material: overwriteMaterial ?
    <meshStandardMaterial attach="material" color={0xa3005c} metalness={1} roughness={0.2} visible={true} /> :
    materials['mat_7']
});

如果overwriteMaterial 为假,它可以工作。它显示了它应该的材料。但如果是真的,那么网格就会消失。

我还想过将&lt;meshStandardMaterial /&gt; 放在网格的儿童道具中。像这样:

return React.cloneElement(mesh, {
  material: overwriteMaterial ? undefined : materials['mat_7'],
  children: overwriteMaterial ? <meshStandardMaterial attach="material" color={0xa3005c} metalness={1} roughness={0.2} visible={true} /> : undefined
});

有了这个我总是得到这个错误,我不知道为什么会出现:

TypeError: Cannot read properties of undefined (reading 'visible')

这种方法能以某种方式起作用还是我做错了什么?

欢迎任何帮助。谢谢

【问题讨论】:

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


    【解决方案1】:

    好吧,在寻找解决方案几个小时后,我自己找到了答案。

    material 属性不接受 JSX 标记。因此,如果您创建 MeshStandardMaterial 类的实例,您可以将其传递给属性,它工作得非常好。现在看起来像这样:

    return React.cloneElement(mesh, {
      material: overwriteMaterial
      ? new MeshStandardMaterial({ color: 0x0ff000 })
      : materials['mat_7']
    })
    

    注意:MeshStandardMaterial 类是从three 包中导出的。

    【讨论】:

      【解决方案2】:

      我真的不认为你必须克隆任何反应元素,这似乎不正确。您可以像在普通的三个应用程序中一样克隆或变异材料。我不知道你为什么要克隆 jsx。

      const { scene } = useGLTF(url)
      const clonedScene = useMemo(() => scene.clone(), [])
      useLayoutEffect(() => {
        clonedScene.traverse(o => {
          if (o.type === 'Mesh') {
            o.material = ...
          }
        })
      }, [clonedScene]}
      return <primitive object={clonedScene} />
      

      您也可以完全跳过 clonedScene,这仅适用于您计划在场景中多次重用模型的情况。

      【讨论】:

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