My current issue involves using the Raycaster in THREE.js to focus on objects with the mouse position. While I've successfully done this many times before, something seems to be off in my current setup.
Strangely, the onFocus callback occasionally triggers, but most of the time it's the onBlur callback that is being called instead. Despite referencing examples and searching through Stack Overflow questions, I can't seem to pinpoint where I'm going wrong. The only notable difference I can find compared to previous instances is that usually, my camera is positioned at 0, 0, 0.0001, facing outwards towards the objects. However, this time around, the camera is placed above and looking down into the objects.
The camera coordinates are set at 130, 325, 194, while the object is located at 0, 0, 0.
Take a look at the code snippets below:
scene = new THREE.Scene();
scene.add(camera);
const geometry = new THREE.CubeGeometry(50, 50, 50);
const material = new THREE.MeshBasicMaterial( { color: 0xff00ff, wireframe: false } );
const mesh = new THREE.Mesh(geometry, material);
mesh.onFocus = () => {
console.log('focus test');
}
mesh.onBlur = () => {
console.log('blur test');
}
intersectableObjects.push(mesh);
scene.add(mesh);
const onMouseMove = ({ clientX, clientY }) => {
const x = (clientX / window.innerWidth) * 2 - 1;
const y = - (clientY / window.innerHeight) * 2 + 1;
mouseVector.set(x, y);
raycaster.setFromCamera(mouseVector, camera);
castFocus();
}
const castFocus = () => {
intersectableObjects.forEach((obj, i) => {
const intersects = raycaster.intersectObject( obj, false );
if (intersects.length) return obj.onFocus();
obj.onBlur();
});
}