How to create a shape when clicking on a plane geometry

I’m trying to create a sphere geometry when I click the plane but where the ray clicks and where the actually mouse.x and y values are off, tried to search online and chatgpt but didn’t solve nor understand the issue.

Here is my code:

// Create a line
function lineCreation(mouse)
{
  console.log("x: " + mouse.x);
  console.log("y: " + mouse.y);
}

const mouse = new THREE.Vector2();
const raycaster = new THREE.Raycaster();

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

  console.log("Mouse NDC:", mouse.x, mouse.y);

  // Debug: Unproject mouse coordinates into world space
  const ndc = new THREE.Vector3(mouse.x, mouse.y, -1).unproject(camera);
  console.log("Mouse in world space:", ndc);

  // Cast a ray
  raycaster.setFromCamera(mouse, camera);
  const intersects = raycaster.intersectObject(plane);

  const debugRay = new THREE.ArrowHelper(raycaster.ray.direction, raycaster.ray.origin, 5, 0xff0000);
  scene.add(debugRay);

  if(intersects.length > 0)
  {
    const position = intersects[0].point;
    console.log("Clicked on plane at:", intersects[0].point);
    lineCreation(ndc);
  }
};

window.addEventListener('click', onMouseClick);

Hi @harp3d

Write me please if is that what You would like?

1 Like

Yes, I want to click on a particular point on the plane and create a sphere or any shape.

But it doesnt get made at the exact spot I click. Something is off with the mouse click coordinates and raycaster coordinates.

I see.

Try this (you may click on the plane or rotate it):

https://codepen.io/boytchev/full/mydzZQV

image

2 Likes

Okay thanks!

What was I doing wrong? Maybe not copying the exact values of intersection.point?

Hi @harp3d

Reviewing your original post and looking at @PavelBoytchev solution, I think I misunderstood your desire to draw shapes.
I made an alternative with lines…

PS: with CTRL+U You see all code.
PS2: You can draw with one old page:

You could debug your code to find where things go wrong, or you could compare it with other working examples (like the one that @jrlazz has posted) and look for any differences.

At a first glance:

  • the code does not use the result of the raycasting intersection intersects[0].point, which is the correct world position of intersection
  • the code does not create any objects, thus noone knows what coordinates you actually use; most likely lineCreation(ndc) is wrong, because ndc are not the world coordinates
1 Like