Issue with Raycaster: Selecting Incorrect Geometry Behind Desired Object

Hi Guys!

I’m encountering an issue with the Raycaster in my Three.js application. When I click on a specific object, the Raycaster is incorrectly selecting the geometry behind it instead of the intended target object. I’ve tried adjusting the render order and other properties, but the problem persists. It seems like there may be factors like transparency or object hierarchy affecting the selection process.

I’d appreciate any insights or suggestions on how to resolve this issue. Please let me know if you need more information or code snippets.

Thank you!

applyDefaults(
    model: Object3D,
    userData: UserData,
    opacity = 1,
    wireframe = false
  ): void {
    model.userData = userData;

    model.traverse((child: Object3D): void => {
      if (child instanceof Mesh) {
        child.userData = userData;
        child.material.metalness = 0;
        child.material.transparent = true;
        child.material.opacity = opacity;
        child.material.wireframe = wireframe;
      }
    });
  }


export function raycast({
  mouse,
  e,
  width,
  height,
  camera,
  scene,
  raycaster
}: Props): UserData | undefined {
  mouse.x = (e.clientX / width) * 2 - 1;
  mouse.y = -(e.clientY / height) * 2 + 1;

  raycaster.setFromCamera(mouse, camera);
  const models = scene.children.filter((model) => model.userData.name);

  let intersectedModel: undefined | UserData = undefined;

  for (const model of models) {
    const intersects = raycaster.intersectObject(model, true);

    if (intersects.length > 0) {
      intersectedModel = intersects[0].object.userData as UserData;
      break;
    }
  }

  return intersectedModel;
}

ezgif.com-optimize

Seem you use a regular loop to cast multiple rays for each objects, this is not necessary and could lead to this result.

Instead push your objects inside an array, then use “s” at the end of your call
raycaster.intersectObjects(modelArray, true);

Not sure this is the issue, but at least the raycasting will evaluate all possible outcome.

Thanks a lot… Absolutely right, this solved the issue but don’t know why instectObject doesn’t work that way… the reason I was using loop was that I use “mousemove” event which hits hard on performance …

1 Like

Your mesh is very complex. To avoid the raycaster to check each face ( native three raycast is not optimized and quickly overloaded ) You have two options: raycast against an invisible “simplified-box” version of each piece, or use a plugin like Three-bvh.

1 Like

Thats pretty impressive