Only start function when hovering certain objects

I use the following code to check when the user is hovering on certain objects:

    $(document).on('mousemove', function(ev) {
    event.preventDefault();
     
    mouse.x = (event.clientX / renderer.domElement.clientWidth) * 2 - 1;
    mouse.y =  - (event.clientY / renderer.domElement.clientHeight) * 2 + 1;
     
    raycaster.setFromCamera(mouse, camera);
    var intersects = raycaster.intersectObjects( objects, true );
    var canvas = document.body.getElementsByTagName('canvas')[0];
    	
    if (intersects.length > 0) {
    		canvas.style.cursor = "pointer";
    	} else {
        canvas.style.cursor = "default";
    	}
    });

This intersects with all items in the array ‘objects’.

Now I’ve made another array, let’s call it ‘orbs’. The items in the ‘orbs’ array are in the ‘objects’ array as well, because they share some functions.

Now I want a certain action to happen when hovering on an item that’s in the ‘orbs’ array, but I’m not able to separate any item from any array. Every item that has raycaster.intersectObjects(xxx , true );
reacts to the hover function. How can I get a hover function for only items in the ‘orbs’ array?

You could use Object3D.userData to tag your orbs items like so:

orb.userData.tag = 'orb';

After performing the intersection test, you can evaluate the first entry in the intersects array and check for the tag. Something like:

if ( intersects[ 0 ].object.userData.tag === 'orb' )

BTW: It’s not recommended for performance reasons to execute the following code every time the mousemove event fires:

var canvas = document.body.getElementsByTagName('canvas')[0];

Instead, query the canvas element once, store it in a variable and then reuse it.

1 Like

Thank you!

I have one error.

This is my code now:
$(document).on(‘mousemove’, function(ev) {
event.preventDefault();

    mouse.x = (event.clientX / renderer.domElement.clientWidth) * 2 - 1;
    mouse.y =  - (event.clientY / renderer.domElement.clientHeight) * 2 + 1;
 
    raycaster.setFromCamera(mouse, camera);
	var intersects = raycaster.intersectObjects( objects, true );
	
    if (intersects.length > 0) {
		canvas.style.cursor = "pointer";
	} else {
        canvas.style.cursor = "default";
	}
	
	if ( intersects[0].object.userData.tag === 'orb' ) {
		canvas.style.cursor = "wait";
	}
});

I temporarily use the cursor style to check if it is working, and it indeed changes! The only problem is I get a console error: Uncaught TypeError: Cannot read property ‘object’ of undefined. How do I get rid of this error?

Fixed it already, forgot to check
if(intersects.length > 0)
at the
if ( intersects[0].object.userData.tag === 'orb' )
statement

1 Like