Skip to content

Instantly share code, notes, and snippets.

@NachoToast
Created September 24, 2023 23:04
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 NachoToast/72a869330b6bd8ca86e036504037775d to your computer and use it in GitHub Desktop.
Save NachoToast/72a869330b6bd8ca86e036504037775d to your computer and use it in GitHub Desktop.
NDC to XYZ Coordinates (ThreeJS)
/*
Translates normalised device coordinates (NCD) to world coordinates.
Calculate NCD using mouseMove/pointerMove event listeners:
mouseX = (e.clientX / window.innerWidth) * 2 - 1;
mouseY = -(e.clientY / window.innerHeight) * 2 + 1;
You can then test if it works by setting up a camera and a cursor mesh object in the scene,
copying its position from the return value every animation frame:
cursorMesh.position.copy(getCursorWorldCoordinates());
If moving the camera around (e.g. from player movement) be sure to run this beforehand.
*/
const _cursorVectorFromCamera = new THREE.Vector3();
const _cursorVectorFromOrigin = new THREE.Vector3();
function getCursorWorldCoordinates(): THREE.Vector3 {
_cursorVectorFromCamera.x = inputController.mouseX;
_cursorVectorFromCamera.y = inputController.mouseY;
_cursorVectorFromCamera.z = 0;
_cursorVectorFromCamera.unproject(camera);
_cursorVectorFromCamera.sub(camera.position).normalize();
_cursorVectorFromCamera.multiplyScalar(-camera.position.y / _cursorVectorFromCamera.y);
return _cursorVectorFromOrigin.copy(camera.position).add(_cursorVectorFromCamera);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment