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);
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;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With