I'm trying to detect when the user has clicked on a specific cube in my 3d scene I've seen a few similar questions but none seem to have quite the same problem as me.
I have a 3D Array of cubes which populates and displays fine but when my mouse down function is called, the intersect array is always empty - I can't see what's wrong and would appreciate any help.
My renderer is set up like so:
function setupRenderer()
{
renderer = new THREE.WebGLRenderer({antialias: true});
renderer.setSize(window.innerWidth, window.innerHeight);
renderer.setClearColorHex( 0xEEEEEE, 1 );
renderer.domElement.addEventListener( 'mousedown', onDocumentMouseMove, false );
$('body').append(renderer.domElement);
}
and the event handler is:
function onDocumentMouseDown(event)
{
console.log("mouse clicked!");
event.preventDefault();
if(event.target == renderer.domElement)
{
var mouseX = (event.clientX / window.innerWidth)*2-1;
var mouseY = -(event.clientY /window.innerHeight)*2+1;
var vector = new THREE.Vector3(mouseX, mouseY, 0.5);
projector.unprojectVector(vector, camera);
var raycaster = new THREE.Raycaster(camera.position, vector.subSelf(camera.position).normalize());
var intersects = raycaster.intersectObjects(cubes);
console.log("intersects.length: " + intersects.length);
if ( intersects.length > 0 ) {
console.log("intersected objects");
/* do stuff */
}
}
}
You can see the current project in action at http://kev-adsett.co.uk/experiments/three.js/experiment1/
You need to pass in a single array of objects into
var intersects = raycaster.intersectObjects( objects );
If the objects array is hierarchal (i.e., one of the objects has a child), then you need to specify it this way:
var intersects = raycaster.intersectObjects( objects, true );
You can also pass in scene.children.
This function will not work with your "cubes" data structure.
three.js r.54
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