I am struggling to figure out the best way to achieve this. While raycasting seems effective in finding points that intersect with objects, I simply want to translate 2D mouse coordinates to a 3D point where the mouse clicks, regardless of scale, rotation, or any objects present.
One idea I considered but have not yet implemented involves creating an invisible plane parallel to the camera, always upright and intersecting the y axis. Then, using a raycaster to hit the plane, draw accordingly, and then remove the plane. However, this method feels inefficient.
Currently, I have a method that works relatively well but encounters issues when the line moves away from the origin or the camera is zoomed.
In the image provided, two lines are drawn from different perspectives. The vertical line shows what happens when the camera aligns with the x and z axes, while the horizontal line demonstrates the result when the camera faces downward. https://i.sstatic.net/MBuhf.png
It appears that the calculation relies on the distance to the camera, resulting in distortion as the line moves farther away. How can this distortion be eliminated?
Source: https://github.com/AskAlice/mandala-3d-threejs Live demo:
Below is the relevant code snippet:
js/content.js@112
function get3dPointZAxis(event)
{
camPos = camera.position;
var mv = new THREE.Vector3((event.clientX / window.innerWidth) * 2 - 1, -(event.clientY/window.innerHeight) * 2 + 1, 1).unproject(camera);
var m2 = new THREE.Vector3(0,0,0);
var pos = camPos.clone();
pos.add(mv.sub(camPos).normalize().multiplyScalar(m2.distanceTo(camPos)));
return pos;
}
This function was developed based on information from two Stack Overflow posts, but it still has the mentioned issues.
Initially, I referred to this post for drawing and converting to the z-axis in a flat manner, though implementing it in three dimensions proved challenging:
How to draw a line segment at run time using three.js
Subsequently, I utilized details from another post to align the object parallel to the camera on the x-z axis like so: https://i.sstatic.net/5mSmb.png
Moving objects parallel to projection plane in three.js