Bruno Boudinski
Bruno Boudinski

Reputation: 83

Three.js / Intersection

In my three.js scene, I have some cubes. I would like to offer possibility to the user to select a box with his mouse.

This the significant code (I use Three.js version 69.) :

function init() {
    [...]
    camera = new THREE.PerspectiveCamera(VIEW_ANGLE,ASPECT,NEAR,FAR);
    [...]
    // in a 'for' iteration, I a many boxes in a 'objects' array :
        abox = new THREE.Mesh( geometry, material );
        objects.push( abox );
    [...]
    vector = new THREE.Vector3(0,0,0);
    raycaster = new THREE.Raycaster();
    animate();  
    document.addEventListener( 'mousedown', onDocumentMouseDown, false     );  
}


function onDocumentMouseDown( event ) {
    event.preventDefault();
    if ( camera instanceof THREE.OrthographicCamera ) {
        vector.set( ( event.clientX / window.innerWidth ) * 2 - 1, - ( event.clientY / window.innerHeight ) * 2 + 1, - 1 );
        vector.unproject( camera );
        dir.set( 0, 0, - 1 ).transformDirection( camera.matrixWorld );
        raycaster.set( vector, dir );
    } else if ( camera instanceof THREE.PerspectiveCamera ) {
        vector.set( ( event.clientX / window.innerWidth ) * 2 - 1, - ( event.clientY / window.innerHeight ) * 2 + 1, 0.5 );
        vector.unproject( camera );
        raycaster.set( camera.position, vector.sub( camera.position ).normalize() );
    }

    var intersects = raycaster.intersectObjects( objects , false);

    if ( intersects.length > 0 ) {

        var intersect = intersects[ 0 ];

        // change color of the face
        intersect.object.material.color.setHex( Math.random() * 0xFF0000 );

        renderer.render(scene, camera);

        }

    }

When I click on a cube, the point (intersect) selected is not exactly (near, but not exactly) where I clicked. There is like a shift, a translation (I tried with an Orthographic or Perpective camera....same problem).

Any help is welcome.

Thanks

Upvotes: 4

Views: 1939

Answers (1)

Bruno Boudinski
Bruno Boudinski

Reputation: 83

As WestLangley suggest to me, the answer was about offset of the canvas. He wrote a nice explanation here THREE.js Ray Intersect fails by adding div

Upvotes: 2

Related Questions