Created
September 24, 2023 23:04
-
-
Save NachoToast/72a869330b6bd8ca86e036504037775d to your computer and use it in GitHub Desktop.
NDC to XYZ Coordinates (ThreeJS)
This file contains hidden or 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
/* | |
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