three.jsraycastingorthographicpicking

three.js orthographic camera object picking


i am trying to pick objects in a scene where i use an orthographic camera. my code fragment already works, but it is not precise. i already found some answers on stackoverflow, but those are deprecated or won't work anymore at all. here is my code onMouseDown

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

    mouse.x = ( event.clientX / window.innerWidth ) * 2 - 1;
    mouse.y = - ( event.clientY / window.innerHeight ) * 2 + 1;

    var vector = new THREE.Vector3(mouse.x, mouse.y, 0.5);
    var pos = camera.position;
    var ray = new THREE.Raycaster(pos, vector.unproject(camera).sub(camera.position).normalize());

    var intersects = ray.intersectObjects(objects);

    if (intersects.length > 0) {
        console.log("touched:" + intersects[0]);
    }
    else {
        console.log("not touched");
    }
}

please see http://jsfiddle.net/ujzpe07t/1/

if you click some pixels away left/right/above/below the cube, it still tells me that the object was touched.

i am using three.js r69.

any hints would be very much appreciated. thanks, cheers!


Solution

  • Here is the pattern to use when raycasting (picking) with either an orthographic camera or a perspective camera:

    var raycaster = new THREE.Raycaster(); // create once
    var mouse = new THREE.Vector2(); // create once
    
    ...
    
    mouse.x = ( event.clientX / renderer.domElement.clientWidth ) * 2 - 1;
    mouse.y = - ( event.clientY / renderer.domElement.clientHeight ) * 2 + 1;
    
    raycaster.setFromCamera( mouse, camera );
    
    var intersects = raycaster.intersectObjects( objects, recursiveFlag );
    

    three.js r.84