Hello,
I’m trying to import a 3D model from Blender using the R3F library, but I can’t visualize the animation. There’s dynamic control of the meshes to insert in the scene because popups will be added later based on the properties of the mesh. By using <primitive> , I manage to see the animation but I lose dynamic control over the meshes. Below is the implemented code:
import React, { useState, useEffect } from 'react';
import { useFrame, useLoader } from '@react-three/fiber';
import { useAnimations } from '@react-three/drei';
import { DRACOLoader } from "three/examples/jsm/loaders/DRACOLoader.js";
import { GLTFLoader } from "three/examples/jsm/loaders/GLTFLoader.js";
export function Model() {
const nodes = useLoader(GLTFLoader, './BIM/prueba_animacion.glb', loader => {
const dracoLoader = new DRACOLoader();
dracoLoader.setDecoderPath('./draco/gltf/');
loader.setDRACOLoader(dracoLoader);
});
console.log(nodes);
const { actions, mixer, ref } = useAnimations(nodes.animations, nodes.scene);
console.log(actions);
const [renderedMeshes, setRenderedMeshes] = useState([] as any);
const renderNestedMeshes: any = (element: any) => { // metodo funzionante per i bim meno complessi
const renderedMeshes: any = [];
element.children.forEach((mesh: any, index: number) => {
console.log(mesh)
let nestedMeshes: any;
if (mesh.children.length > 0) {
nestedMeshes = renderNestedMeshes(mesh);
}
let res =
<mesh.type
key={`${mesh.uuid}`} // Ensure unique key for each child mesh
castShadow
receiveShadow
geometry={mesh.geometry}
material={mesh.material}
position={mesh.position}
rotation={mesh.rotation}
scale={mesh.scale}
name={mesh.name}
>
{nestedMeshes}
</mesh.type>
;
renderedMeshes.push(res)
})
return renderedMeshes;
};
const getMeshes: any = () => {
setRenderedMeshes(renderNestedMeshes(nodes.scene))
}
useEffect(() => {
getMeshes();
}, []);
useEffect(() => {
console.log(actions);
actions.CubeAction?.play();
}, [actions]);
return (
<group dispose={null} >
{renderedMeshes}
</group>
);
}
export default function Component3D () {
return (
<Model />
);
};
I’m not sure if the only way to import the animations is through <primitive> or if there’s a solution to my case. I would appreciate it if you could help me find a solution. Thanks in advance!