Skip to content

Instantly share code, notes, and snippets.

@duhaime
Created June 2, 2019 15:47
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save duhaime/99ee7b53c61a8153bd8f7eafaf8a8334 to your computer and use it in GitHub Desktop.
Save duhaime/99ee7b53c61a8153bd8f7eafaf8a8334 to your computer and use it in GitHub Desktop.
three.js unproject unprojection event to world coords
function getWorldCoords(e) {
// identify the x,y coords in canavs that got event
var rect = canvas.getBoundingClientRect(),
x = e.clientX - rect.left,
y = e.clientY - rect.top;
// convert x,y to clip space in canvas:
// canvas coords from top left in clockwise order
// (-1,1), (1,1), (-1,-1), (1, -1)
var mouse = new THREE.Vector3();
mouse.x = ( (x / canvas.clientWidth ) * 2) - 1;
mouse.y = (-(y / canvas.clientHeight) * 2) + 1;
mouse.z = 0.5; // set to z position of mesh objects
// reverse projection from 3D to screen
mouse.unproject(camera);
// convert from point to a direction
mouse.sub(camera.position).normalize();
// scale the projected ray
var distance = - camera.position.z / mouse.z,
scaled = mouse.multiplyScalar(distance),
coords = camera.position.clone().add(scaled);
return coords;
}
renderer.domElement.addEventListener('click', getWorldCoords)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment