Can't select object on mouse click

Hi everyone. I am very new to three.js, and I am working on a project that uses gltf models. I have a world map and 3D model pins that contain an avatar using textureLoader.load(image). When the mouse hovers over the pins, a popover appears with some information and the avatar. I wanted to make this pin clickable, so it redirects to another page and I used raycaster. However, it doesn’t behave as I would want it to. I have to click on a very specific point, where the pin meets the surface of the map, in order to be redirected to another page. Also, I want the pin model to be clickable, which is not the case right now. The globe is composed of different objects with different names and the problem is that when I click on the pin, intersects[0].object.name, does not pick up the name of the pin as if it doesn’t exist. I can’t figure out what the problem is.

Here is a screenshot of my map with markers.

  const onPinClick = React.useCallback(
    (event: MouseEvent) => {
      event.preventDefault();
      if (threeData.current === null) {
        return;
      }
      const { scene, camera, renderer } = threeData.current;
      const raycaster = new Raycaster();
      const mouse = new Vector2();
      if (!threeData.current) {
        return;
      }

      mouse.x = (event.clientX / window.innerWidth) * 2 - 1;
      mouse.y = -(event.clientY / window.innerHeight) * 2 + 1;

      raycaster.setFromCamera(mouse, camera);
      const intersects = raycaster.intersectObjects(scene.children, true);
      const pins = scene.children.find((child) => child.name === 'pins');

      renderer.render(scene, camera);

      if (intersects.length > 0 && pins) {
        if (pins.children.find((child) => child.data.user.country.name === intersects[0].object.data.countryName)) {
          router.push('/profile');
        }
      }
    },
    [router],
  );

Any help is much appreciated.

1 Like

@Rama Hi, I has that problem to when i try to do raycasting with gltf objects. Reason of this problem is that the raycasting doesn’t work with SkinnedMeshes. And how many we trying to do raycasting with gltf objects there are probability that we have SkinedMeshes and raycasting doesn’t work right.

const sceneMeshes = []
////
scene.children.forEach(gltfMesh => {
const sceneMesh = gltfMesh as THREE.Mesh //needs Typescript
sceneMeshes.push(sceneMesh)
////

const onClickPick = React.useCallback(
 (event: MouseEvent) => {
  /////
  const intersects = raycaster.intersectObjects(sceneMeshes, true);
  /////
}

I see that you use react. Also you can use React-Three-Fiber for working with react and ThreeJS. It is good renderer from react for creating three.js meshes like react components

2 Likes