如何在三个ejs或反应三光纤中加载相同的gltf模型



我用的是三反应纤维,我想做一个房子。因此,我使用GLTF模型来显示门。

渲染一扇门是好的,但是当我从同一个GLTF文件渲染2扇门时,只有第二扇门被渲染。看起来第二扇门已经取代了第一扇门,而不是一扇新门。

我怎么能实现有多个门,我已经搜索,但似乎没有人问这个问题??

我代码:

Door.tsx

import React from 'react';
import { useLoader } from "@react-three/fiber";
import { GLTFLoader } from 'three/examples/jsm/loaders/GLTFLoader';
interface DoorProps {
rotation: any;
}
function Door(props: DoorProps) {
const gltf = useLoader(GLTFLoader, '/simple_door.gltf');
return (
<>
<primitive
object={gltf.scene}
position={[25, 1, -17]}
scale={0.05}
rotation={props.rotation}
/>
</>
);
}
export default Door;

Room.tsx

function Room() {
return (
<Canvas
shadows
dpr={[1, 2]}
frameloop="demand"
style={{ height: 800 }}
camera={{ fov: 75, near: 0.1, far: 1000, position: [0, 10, 20] }}
>
<OrbitControls addEventListener={undefined} hasEventListener={undefined} removeEventListener={undefined} dispatchEvent={undefined} />
<ambientLight intensity={0.8} />
<color attach="background" args={['#d0d0d0']} />
<fog attach="fog" args={['#d0d0d0', 100, 600]} />
<Suspense fallback={null}>
<Environment preset="city" />
<Door />
<Plane 
width={50}
height={10}
depth={1}
position={[0, 0, -20]}
/>
<Door
rotation={[0, 90*Math.PI/180, 0]}
/>
<Plane 
width={50}
height={1}
depth={50}
position={[0, -4.5, 5]}
/>
</Suspense>
</Canvas>
);
};
export default Room;

看起来你想克隆你的3D门模型,

有几种方法可以做到这一点,您正在寻找的可能是简单使用克隆函数:

import React from 'react';
import { useGraph } from '@react-three/fiber'
import { useGLTF } from '@react-three/drei'
import { SkeletonUtils } from "three/examples/jsm/utils/SkeletonUtils"
interface DoorProps {
rotation: any;
}
function Door(props: DoorProps) {
const { scene, materials, animations } = useGLTF('/simple_door.gltf');
const clone = useMemo(() => SkeletonUtils.clone(scene), [scene])
const { nodes } = useGraph(clone)
return (
<>
<primitive
object={nodes}
position={[25, 1, -17]}
scale={0.05}
rotation={props.rotation}
/>
</>
);
}
export default Door;

我使用了drei包,因为如果需要的话,它可以帮助加载模型以外的其他信息

下面是另一个例子:https://codesandbox.io/s/react-three-fiber-wildlife-nrbnq?file=/src/Model.js

你可能还想显示很多门,在这种情况下,我建议你使用instancedMesh而不是原始的

还有一个工具,可以帮助你创建你的门组件将是gltfjsx,看看它:https://www.npmjs.com/package/gltfjsx

您不能在两个地方添加相同的模型,三个ejs将从第一个地方自动卸载它。解决方案是gltfjsx。这允许您重用模型。在香草三中没有对应的,它们通常重新解析和/或克隆。使用GLTFJSX,模型只加载和解析一次,但由于它是不可变的,您可以随时重用它。

这里有一个例子:https://codesandbox.io/s/re-using-gltfs-dix1y GLTFJSX甚至可以生成实例,所以无论你渲染多少次,你都只有一个drawcall。

第一扇门没有通过rotation道具,

如果你不想把rotationprop传递给First Door,让旋转像这样成为一个可选的道具。

interface DoorProps {
rotation?: any;
}

最新更新