Skip to content

Instantly share code, notes, and snippets.

@jensarps
Created August 9, 2012 11:07
Show Gist options
  • Save jensarps/3303293 to your computer and use it in GitHub Desktop.
Save jensarps/3303293 to your computer and use it in GitHub Desktop.
Mouse-Picking Collada Models with THREE.js
container.addEventListener('click', function (evt) {
// The user has clicked; let's note this event
// and the click's coordinates so that we can
// react to it in the render loop
clickInfo.userHasClicked = true;
clickInfo.x = evt.clientX;
clickInfo.y = evt.clientY;
}, false);
// Unproject the vector
projector.unprojectVector(directionVector, camera);
// Substract the vector representing the camera position
directionVector.subSelf(camera.position);
var intersects = ray.intersectObjects(scene.children);
if (intersects.length) {
// intersections are, by default, ordered by distance,
// so we only care for the first one. The intersection
// object holds the intersection point, the face that's
// been "hit" by the ray, and the object to which that
// face belongs. We only care for the object itself.
var target = intersects[0].object;
statsNode.innerHTML = 'Name: ' + target.name
+ '<br>'
+ 'ID: ' + target.id;
}
// Normalize the vector, to avoid large numbers from the
// projection and substraction
directionVector.normalize();
// Now our direction vector holds the right numbers!
ray.setSource(camera.position, directionVector);
// The following will translate the mouse coordinates into a number
// ranging from -1 to 1, where
// x == -1 && y == -1 means top-left, and
// x == 1 && y == 1 means bottom right
var x = ( clickInfo.x / SCREEN_WIDTH ) * 2 - 1;
var y = -( clickInfo.y / SCREEN_HEIGHT ) * 2 + 1;
// Now we set our direction vector to those initial values
directionVector.set(x, y, 1);
var ray = new THREE.ReusableRay();
var projector = new THREE.Projector();
var directionVector = new THREE.Vector3();
var SCREEN_HEIGHT = window.innerHeight;
var SCREEN_WIDTH = window.innerWidth;
var clickInfo = {
x: 0,
y: 0,
userHasClicked: false
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment