Question

For some reason, in the code below, the "intersects" variable does not contain any items in the onDocumentMouseDown event handler when I simply click an object. In order for it to detect the object clicked, I have to click and slightly drag the mouse before it picks up the item clicked. I am also using trackballcontrols if that matters. I have a jsfiddle example here: http://jsfiddle.net/marktreece/xvQ3f/

In the jsfiddle example, click on the cube and notice that the color does not change as expected. Now click the cube and before releasing the mouse button, move it slightly and the color changes. How can I make it so that simply clicking the object will be enough?

Here is my mousedown event handler:

function onDocumentMouseDown( event ) {
    event.preventDefault();
    var vector = new THREE.Vector3( ( event.clientX / window.innerWidth ) * 2 - 1, - ( event.clientY / window.innerHeight ) * 2 + 1, 0.5 );
    projector.unprojectVector( vector, camera );
    var raycaster = new THREE.Raycaster( camera.position, vector.sub( camera.position ).normalize() );
    var intersects = raycaster.intersectObjects( scene.children, true );
    if ( intersects.length > 0 ) {
        intersects[ 0 ].object.material.color.setHex( Math.random() * 0xffffff );
    }
}
Was it helpful?

Solution

From what I can see, in your example raycasting works fine and intersects variable is not empty. The problem is that as you are using TrackballControls, the rendering is performed only when the camera changes its position. That is why a small drag of the mouse results in changing the color of the box.

Below I included your animate function with one new call to render function. This solves the problem. However, note that this is not the most efficient solution as the rendering is performed every frame.

function animate() {
    try{
        requestAnimationFrame( animate );
        controls.update();
        render();
    }
    catch(err){
        alert("animate error. " + err.message);
    }
}

Hope this helps!

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top