Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Converting 2D mouse coordinates to world XZ coordinates in ThreeJS

I need to convert mouse screen coordinates to ThreeJS world coordinates on XZ plane.

I found this working code to convert the mouse position to XY world coordinates but I don't know how to modify it to get XZ coordinate:

var vector = new THREE.Vector3();
vector.set((event.clientX / window.innerWidth) * 2 - 1, - (event.clientY / window.innerHeight) * 2 + 1, 0.5);
vector.unproject(camera);
var dir = vector.sub(camera.position).normalize();
var distance = - camera.position.z / dir.z;
var position = camera.position.clone().add(dir.multiplyScalar(distance));
console.log("x: " + position.x + " y: " + position.y);
like image 663
Jarzka Avatar asked Mar 14 '23 13:03

Jarzka


1 Answers

Got it by modifying code found from here: http://www.osd.net/blog/web-development/3d-board-game-in-a-browser-using-webgl-and-three-js-part-3/

                var x, y;
            //
            if (event.offsetX !== undefined) {
                x = event.offsetX;
                y = event.offsetY;
            } else {
                x = event.layerX;
                y = event.layerY;
            }

            var pos = new THREE.Vector3(0, 0, 0);
            var pMouse = new THREE.Vector3(
                ( event.clientX / window.innerWidth ) * 2 - 1,
                - ( event.clientY / window.innerHeight ) * 2 + 1,
                1);
            //
            var projector = new THREE.Projector();
            projector.unprojectVector(pMouse, camera);

            var cam = camera.position;
            var m = pMouse.y / ( pMouse.y - cam.y );

            pos.x = pMouse.x + ( cam.x - pMouse.x ) * m;
            pos.z = pMouse.z + ( cam.z - pMouse.z ) * m;
like image 59
Jarzka Avatar answered Apr 06 '23 16:04

Jarzka