How to get touched position of texture image on THREE.SphereGeometry

I want to get touched position of threejs’s Object3D (THREE.SphereGeometry).

I could get intersect object from THREE.Raycaster but what I really want is X/Y coordinates of the image which is used by Geometry as a Texture.

How can I convert the intersect object to X/Y coordinates of the texture image of the sphere geometry?

I wish this image helps you understand this question.

Thank you @prisoner849 and @Mugen87. I read your comments and tried intersection.uv after reading source code of raycast texture sample.

But I could not get correct value from intersect object.

Here is my sample app (Script will run after clicking Detect Faces)

I created mesh object like:

    const sphereMesh = (() => {
      const geometry = (() => {
        const geometry = new THREE.SphereGeometry(100, 64, 64);

        geometry.scale(1, 1, -1);
        geometry.rotateY(Math.PI / 2);

        return geometry;
      })();

      const material = (() => {
        const material = new THREE.MeshBasicMaterial({
          wireframe: true,
        });

        return material;
      })();

      const mesh = new THREE.Mesh(geometry, material);

      mesh.name = "sphere";

      return mesh;
    })();

then set texture on the material:

    async function resetImageTexture() {
      const texture = new THREE.Texture();

      texture.image = previewImage;
      texture.format = THREE.RGBFormat;
      texture.needsUpdate = true;

      sphereMesh.material.wireframe = false;
      sphereMesh.material.map = texture;
    }

and get intersect object and converted to pixel coordinates.

                  raycaster.setFromCamera(position, camera);

                  const intersects = raycaster.intersectObject(sphereMesh);

                  if (intersects[0]) {
                    const uv = sphereMesh.material.map.transformUv(intersects[0].uv);

                    previewCanvasContext.beginPath();
                    previewCanvasContext.arc(uv.x * previewCanvas.width, uv.y * previewCanvas.height, 20, 0, Math.PI * 2);
                    previewCanvasContext.closePath();
                    previewCanvasContext.fill();
                  }

but the result is:

Screenshot

15 thoughts on “How to get touched position of texture image on THREE.SphereGeometry”

  1. The intersection object does not only contain the intersection point in 3D space. It also provides the texture coordinates at the point of intersection. This is documented in the respective documentation page.

    So instead of accessing intersection.point, try it with intersection.uv.

    Reply

Leave a Comment