2
votes

I am generating a bunch of spheres using three.js through an array and a for loop. The original array looks like:

atoms = [
 ['Na', [0, 0, 0]],
 ['Na', [0.5, 0.5, 0]],
 ['Na', [0.5, 0, 0.5]],
 ['Na', [0, 0.5, 0.5]],
 ['Cl', [0.5, 0, 0]],
 ['Cl', [0, 0.5, 0]],
 ['Cl', [0, 0, 0.5]],
 ['Cl', [0.5, 0.5, 0.5]],
];

And i parse the data so that the 3 numbers represent the x, y, z coordinate.

The end product is controlled by orbitcontrols.js and looks like: enter image description here

What I was wondering is how would I go about doing this: mouse over a sphere (while pressing a certain key as to not interfere with orbitcontrols) then upon a mouse click return the xyz of the sphere i clicked on.

1

1 Answers

2
votes

First of all you will need to add some eventListeners for the keydown, keyup and mousedown events:

document.addEventListener('keydown', onKeyDown, false);
document.addEventListener('keyup', onKeyUp, false);
document.addEventListener('mousedown', onMouseDown, false);

You can add these eventListeners in your scene, or in some class. For the keyup and keydown you need to lookup the keyCode you want to use.

For the click event you need to use the THREE.Raycaster. You could use something like this as a start:

function onMouseDown(event) {
    event.preventDefault();

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

    var raycaster = new THREE.Raycaster(camera.position, vector.sub(camera.position).normalize());

    for (var i=1; i<=16; i++) {
        var intersect = raycaster.intersectObject(spheres[i]);
        if (intersect.length > 0) {
            console.log(spheres[i].position);
            break;
        }
    }
}

You will need to tweak the vector if you are not using fullscreen.

Hope this helps.