Skip to content Skip to sidebar Skip to footer

Three.js - Getting The X, Y, And Z Coordinates Of Mouse Click

I'm using version 68 of three.js. I would like to click somewhere and get the X, Y, and Z coordinates. I followed the steps here, but they give me a Z value of 0: Mouse / Canvas X,

Solution 1:

You should use a THREE.Raycaster for this. When you set a list of intersectObjects you will be able to get an array of objects that intersected with the ray. So you can get the position from the 'clicked' object from returned list. Check the updated fiddle here. I also changed your Three.js to version R68

For more advanced use of THREE.RayCaster check the examples at Threejs.org/examples like this example with interactive cubes.

Relevant code from the updated fiddle:

functiongetMousePosition(clientX, clientY) {
    var mouse2D = newTHREE.Vector3();
    var mouse3D = newTHREE.Vector3();
    mouse2D.x = (clientX / window.innerWidth) * 2 - 1;
    mouse2D.y = -(clientY / window.innerHeight) * 2 + 1;
    mouse2D.z = 0.5;
    mouse3D = projector.unprojectVector(mouse2D.clone(), camera);
    return mouse3D;
    var vector = newTHREE.Vector3(
    (clientX / window.innerWidth) * 2 - 1, -(clientY / window.innerHeight) * 2 + 1,
    0.5);

    projector.unprojectVector(vector, camera);
    var dir = vector.sub(camera.position).normalize();
    var distance = -camera.position.z / dir.z;
    var pos = camera.position.clone().add(dir.multiplyScalar(distance));
    return pos;
}

functiononDocumentMouseUp(event) {
    event.preventDefault();

    var mouse3D = getMousePosition(event.clientX, event.clientY);
    console.log(mouse3D.x + ' ' + mouse3D.y + ' ' + mouse3D.z);

var vector = newTHREE.Vector3( mouse3D.x, mouse3D.y, 1 );    
    raycaster.set( camera.position, vector.sub( camera.position ).normalize() );

    var intersects = raycaster.intersectObjects(scene.children );
    if(intersects.length > 0){
        console.log(intersects[0].object.position);
    }
}

functionanimate() {
    requestAnimationFrame(animate);
    render();
}

functionrender() {
    renderer.render(scene, camera);
}

Post a Comment for "Three.js - Getting The X, Y, And Z Coordinates Of Mouse Click"