Just getting into Three.js
I'm attempting to load a GLTF model and add mouseover and mouseout events. The goal is for the color of the GLTF model to change on mouseover and revert back to the original on mouseout.
I have had some success with this, but there seems to be a problem as shown in this video. It only changes the color when the mouse pointer directly enters the GLTF model without passing through the black background first.
The code I'm currently using:
const loader = new GLTFLoader();
loader.load('models/box.glb', function (gltf) {
gltf.scene.traverse(function (child) {
if (child.isMesh) {
let m = child;
m.receiveShadow = true;
m.castShadow = true;
m.material.flatShading = true;
sceneMeshes.push(m);
}
if (child.isLight) {
let l = child;
l.castShadow = true;
l.shadow.bias = -.003;
l.shadow.mapSize.width = 2048;
l.shadow.mapSize.height = 2048;
}
});
scene.add(gltf.scene);
console.log(gltf.scene);
}, (xhr) => {
console.log((xhr.loaded / xhr.total * 100) + '% loaded');
}, (error) => {
console.log(error);
});
const raycaster = new THREE.Raycaster();
const sceneMeshes = new Array();
renderer.domElement.addEventListener('mouseover', onMouseMove, false);
renderer.domElement.addEventListener('mouseout', onMouseOut, false);
function onMouseMove(event) {
const mouse = {
x: (event.clientX / renderer.domElement.clientWidth) * 2 - 1,
y: -(event.clientY / renderer.domElement.clientHeight) * 2 + 1
};
raycaster.setFromCamera(mouse, camera);
const intersects = raycaster.intersectObjects(sceneMeshes, false);
if (intersects.length > 0) {
intersects[0].object.material.color.set(0xffff00);
}
}
function onMouseOut(event) {
const mouse = {
x: (event.clientX / renderer.domElement.clientWidth) * 2 - 1,
y: -(event.clientY / renderer.domElement.clientHeight) * 2 + 1
};
raycaster.setFromCamera(mouse, camera);
const intersects = raycaster.intersectObjects(sceneMeshes, false);
if (intersects.length > 0) {
intersects[0].object.material.color.set(0xff0000);
}
}
Any suggestions on what might be causing this issue?