Created
June 2, 2019 15:47
-
-
Save duhaime/99ee7b53c61a8153bd8f7eafaf8a8334 to your computer and use it in GitHub Desktop.
three.js unproject unprojection event to world coords
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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