Highlight objects that are intersected with the raycaster

Hi all,
I’m trying to create something like the raycaster / object selector of https://glb-viewer.blogspot.com/ I want to identify and highlight those objects that are intersected with the raycaster. Here is my javascript code

Can someone help me?

1 Like

Maybe this helps



This topic is discussed quite frequently

Thanks this did help. I have only one question left, When I click on the object is it possible to get the first one back? Here is my JavaScript code, see onClick function. And if I set color when i click. and then click somewhere else, it it pissible to get the original color back

By first, do you mean the nearest? The intersectsObject function returns an array with all objects that were hit. It is sorted from the nearest to the furthest. So you should actually already get the nearest object because you get the first element from intersects[0]

const intersects = raycaster.intersectObjects( scene.children, true );

if (intersects.length > 0) {

    object = intersects[0].object; // index = 0 is the first and nearest obj hit from the raycaster beam
}

if you want to get the original color back, you need to store it in a variable before changing the color. You can use the userData obj which every threejs obj has. Or store it in a global variable

    // Store color in the userData
    object.userData.color = object.material.color.getHex()

    // OR store it in a global variable
    let objColor;

    onClick() {
    
        ...
       
        objColor = object.material.color.getHex()

    }
1 Like

ah oke thanks!!

probably not what you’re looking for but just to give you an option, this stuff is trivial in r3f: https://codesandbox.io/s/floating-shoe-mz11v?file=/src/App.js

  const [active, setActive] = useState(false)
  const [hovered, setHovered] = useState(false)
  return (
    <mesh
      onPointerOver={() => setHovered(true)}
      onPointerOut={() => setHovered(false)}
      onPointerMissed={() => setActive(false)}
      onClick={() => setActive(!active)}>

in vanilla it’s hard and brings about some issues regarding separation of concern: the part of your app that deals with events and raycasting will have to know about your models, everything quickly turns into a cobweb. in the example above you have a self contained, re-usable unity.