在ThreeJS中将2D鼠标坐标转换为世界XZ坐标

时间:2015-10-06 14:51:27

标签: javascript three.js

我需要将鼠标屏幕坐标转换为XZ平面上的ThreeJS世界坐标。

我发现这个工作代码将鼠标位置转换为XY世界坐标,但我不知道如何修改它以获得XZ坐标:

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);

1 个答案:

答案 0 :(得分:6)

通过修改从这里找到的代码得到它: 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;