Raycaster do action when specific object is selected

Hello fellow coders :raised_hand_with_fingers_splayed: I have a question related to raycaster.

In my scene, I have a few objects, and one of them is group named “gele” (means flower in my native language) (on the table):

What I want is to do specific action when flower is clicked. I have tried this by setting a name for my flower group:

gele.name = "flower";

And then in the raycaster function I tried to check it like this:

function onMouseDown( event ) {
raycaster.setFromCamera( mouse, camera );
intersects = raycaster.intersectObjects( scene.children, true );
for ( var i = 0; i < intersects.length; i++ ) {
    if(intersects[ i ].object != plane){
    //intersects[ i ].object.material.color.set( Math.random() * 0xffffff );
//checking if flower is clicked
    if(intersects[ i ].object.parent.name == "flower"){
        window.location.href ='https://www.google.com/';

However, this does not seem to work.

Is there any way to check what object is clicked and only if object matches some specific name, do some actions?

Whole JS code can be seen here: Raycaster - Pastebin.com

Can you also share your code as a git repo? In this way, it’s easier to debug it :innocent:

Sure, here you go: GitHub - morphixas/threejs-raycaster: Learning threejs and raycaster

Haven’t used git that much, just learning now, so let me know if something is not working right or some files didn’t upload properly :pray:

You assume here that all meshes that forms the flower are a direct child of the flower group. However, this is only true for the leaf. The meshes you create with createStem(), createVase() and createStem() are actually Group objects (because SceneUtils.createMultiMaterialObject returns an object of type Group). Have you tried to click on the leaf? The redirect to Google works :wink:.

Instead of changing the way how you generate the flower, I would change the raycasting to this:

intersects = raycaster.intersectObject( gele, true );

if ( intersects.length > 0 ) {

    window.location.href = 'https://www.google.com/';


So try to perform the raycasting with concrete objects and not with the entire scene. This is actually more performant since you save unnecessary intersection tests.

BTW: You can compute the mouse vector in the onMouseDown() listener, too. No need to do this in onMouseMove().

1 Like

Oh wow, I would never have worked that out myself, so that’s why it wasn’t working, because MultiMaterial returns a Group. Hats down to you sir, as it is said: “the more you know” :rainbow: :nerd_face:

Did it according to your suggestion, works well now, cheers!