简体   繁体   中英

How can I interact with objects in the scene in three.js?

For instance, if I point with the mouse at a circle in the scene, being able to detect that. I have looked everywhere and can't seem to find anything. Three.js documentation doesn't really talk about it either.

Firstly you should add Event Listeners like 'mousemove', 'mousedown'.

document.addEventListener('mousedown', onDocumentMouseDown, false);
document.addEventListener('mousemove', onDocumentMouseMove, false); 

So you want an event while moving your mouse over the circle. So lets make an alert that on mouse move on that circle you will get an alert.

function onDocumentMouseDown(event) {

    event.preventDefault();

    mouseYOnMouseDown = event.clientY - windowHalfY;
    mouseXOnMouseDown = event.clientX - windowHalfX;

    var vector = new THREE.Vector3((event.clientX / window.innerWidth) * 2 - 1, -(event.clientY / window.innerHeight) * 2 + 1, 0.5);
    vector = vector.unproject(camera);

    var raycaster = new THREE.Raycaster(camera.position, vector.sub(camera.position).normalize());
    var intersects = raycaster.intersectObjects(circleObj, true); // Circle element which you want to identify

    if (intersects.length > 0) {
        alert("Mouse on Circle");
    }

}

In three.js we use raycaster to point any object. Go through the raycaster in three.js documentation.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM