When loading a gltf model, I want to make sure that a mesh is only displayed when the object is hovered over. I have successfully managed to change its material color using
INTERSECTED.material.color.setHex(radioHoverColor);
and reset it once the mouse leaves the object.However, I am struggling to figure out how to remove the mesh once the mouse moves away from the object.
The mesh just remains in the scene.
I tried adding
scene.remove(radioOutline.mesh)
, but it does not work outside the if statement. If I move all the radioOutline code outside the if statement, it throws an error stating that intersects[0] is undefined, which is understandable.
I have provided an example hosted on GitHub with GitHub Pages integration.
var radioMaterial = new THREE.MeshBasicMaterial({color: 0x0fffAA, side: THREE.BackSide});
class outlineMesh {
constructor(geometry) {
this.mesh = new THREE.Mesh(geometry, radioMaterial);
}
}
// https://github.com/stemkoski/stemkoski.github.com/blob/master/Three.js/Mouse-Over.html
// Mouse hover event -> raycaster
function onHover(event) {
event.preventDefault();
raycaster.setFromCamera( mouse, camera );
var intersects = raycaster.intersectObject( radioModel );
if ( intersects.length > 0 ) {
let radioOutline = new outlineMesh(intersects[0].object.geometry);
radioOutline.mesh.position.set(1.4,-0.5,1.2);
radioOutline.mesh.rotation.y = -0.3;
radioOutline.mesh.scale.multiplyScalar(1.6);
scene.add(radioOutline.mesh);
if ( intersects[0].object != INTERSECTED ) {
if ( INTERSECTED ) {
INTERSECTED.material.color.setHex(INTERSECTED.currentHex);
}
INTERSECTED = intersects[0].object;
INTERSECTED.currentHex = INTERSECTED.material.color.getHex();
INTERSECTED.material.color.setHex(radioHoverColor);
cursor.style.cursor = "pointer";
}
} else {
if ( INTERSECTED ) {
INTERSECTED.material.color.setHex(INTERSECTED.currentHex);
}
INTERSECTED = null;
cursor.style.cursor = "default";
}
}