I’m kind of new to Three.js
I’m trying to load GLTF model, add mouseover and mouseout events, where first will change the GLTF color, while the second will revert it back to the original.
So far I have been able to achieve it - partially, as it appear in this video, it doesn’t change anything, unless the mouse pointer come from (out of focus maybe?) directly into the GLTF model without going through the black background.
The code I’m 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 idea what i might be done wrong?