I want to realize a function that changes color when the mouse is over each mesh part loaded from an Rhino3dm
file with react-three-fiber
.But in the code below mouse events are not working properly for some reason.
For GLTF, using Object.values(gltf.nodes).map
worked fine.
enter image description here
For Rhino3dm, I use object.children.map
and I think this is bad.
Do you know the cause and solution?
This is the sandbox URL. https://codesandbox.io/s/test-rhino3dmloader-wnrty6?file=/src/App.js
import "./styles.css";
import * as THREE from "three";
import { useEffect, useMemo, useRef, useState } from "react";
import { Canvas } from "@react-three/fiber";
import { useLoader } from "@react-three/fiber";
import { Rhino3dmLoader } from "three/examples/jsm/loaders/3DMLoader";
import { Environment, OrbitControls} from "@react-three/drei";
import { GLTFLoader } from "three/examples/jsm/loaders/GLTFLoader";
import { Suspense } from "react";
const Part = (child) => {
const objRef = useRef();
const [hovered, setHover] = useState(false);
const material = new THREE.MeshStandardMaterial({
color: hovered ? "hotpink" : "orange"
});
return (
<mesh
key={child.id}
ref={objRef}
castShadow
receiveShadow
onPointerOver={(e) => {
e.stopPropagation();
setHover(true);
}}
onPointerOut={(e) => {
e.stopPropagation();
setHover(false);
}}
>
<primitive object={child} material={material} />
</mesh>
);
};
const Model = () => {
// For some reason mouse events don't work well in Rhino3dm.
const object = useLoader(Rhino3dmLoader, "./rhino_logo.3dm", (loader) => {
loader.setLibraryPath("https://cdn.jsdelivr.net/npm/rhino3dm@0.15.0-beta/");
});
const model = object.children.map((child) => Part(child));
// For gltf the below code worked fine.
/*
const gltf = useLoader(GLTFLoader, "./rhino_logo.glb");
const model = Object.values(gltf.nodes).map((child) => {
if(child.isMesh){
return Part(child)
}
});
*/
return model;
};
export default function App() {
return (
<div className="App">
<Canvas>
<Suspense fallback={null}>
<Model />
<OrbitControls />
<Environment preset="sunset" background />
</Suspense>
</Canvas>
</div>
);
}
I was able to solve it below! Thank you!!