I would like to change the color of a mesh with each click, I manage a rack in a warehouse
you have to traverse the scene and find them back via name or other characteristics:
scene.getObjectByName("thing")
this changes drastically if you use three with react because it can express your model declaratively, your scene looks like an SVG and you can alter it as your like.
for instance, this example loads a shoe model: Re-using GLTFs - CodeSandbox
it then inserts a custom material for the outer mesh. now you can re-use it while being able to have different colors on each variant:
Thank you for your reply. However I donât use react but rather threejs and typescript , so do I have to use react to do this?
as i said, traversal: scene.getObjectByName(âthingâ) itâs not optimal, and it forces you to mutate the data which then makes it less re-usable, but there is no other way.
loader.load(
âmodels/entrepot.glbâ,
function (gltf) {
gltf.scene.traverse(function (child) {
if ((child as THREE.Mesh).isMesh) {
const m = child as THREE.Mesh
m.receiveShadow = true
m.castShadow = true;
(m.material as THREE.MeshStandardMaterial).flatShading = true
m.material = new THREE.MeshStandardMaterial({color: 0xffffff * Math.random()});
//I can add a listener for each mesh here ??
m.addEventListener(âdblclickâ,function(){
console.log(âmesheName --â+m.name);
})
sceneMeshes.push(m)
}
if ((child as THREE.Light).isLight) {
const l = child as THREE.Light
l.castShadow = true
l.shadow.bias = -0.003
l.shadow.mapSize.width = 2048
l.shadow.mapSize.height = 2048
}
})
scene.add(gltf.scene)
// sceneMeshes.push(gltf.scene)
},
(xhr) => {
console.log((xhr.loaded / xhr.total) * 100 + â% loadedâ)
},
(error) => {
console.log(error)
}
)
here is the code to display the gltf file, why the event listener for the doubleclick does not work?? or i canât add a listener like this directly?? the goal is to listen to the click dynamically, if we are going to use the scene.getObjectByName(âthingâ) method, we must add to all the meshes manually??
threejs doesnât have events, youâll have to write it yourself using raycasting: Threejs basic example - CodeSandbox