2
votes

i currently have a three.js scene in a twitter bootstrap environment, so the renderer.domelement can resize and change its position dependent on screen resolution, browser window size and so on.

Now i have problems using the three.js raycaster to intersect objects in this scene. When the page loads and the scene is shown on the screen the raycaster works fine, but when i scroll the browser window and/or resize it so that the scene is at a different position in the browser window, the intersection of objects doesn't work anymore.

i have no idea how to fix this issue...does someone have an idea how i can fix this?

This is how my Raycaser aktually looks like:

var container = document.getElementById( 'view' );

///Raycaster///

    var projector = new THREE.Projector();

    function onDocumentMouseDown(event) {

        var mouseX = ( ( event.clientX - container.offsetLeft ) / container.clientWidth ) * 2 - 1;
        var mouseY = - ( ( event.clientY - container.offsetTop ) / container.clientHeight ) * 2 + 1;

        var vector = new THREE.Vector3(mouseX, mouseY, 0.5);
        projector.unprojectVector(vector, camera);

        var raycaster = new THREE.Raycaster(camera.position, vector.sub(camera.position).normalize());

        var intersects = raycaster.intersectObjects(objects);

        if (intersects.length > 0) {

            // do something

            var origin = raycaster.ray.origin.clone();
            console.log(origin);

            }
        }

}
2

2 Answers

2
votes

Try this :

let canvasBounds = this.engine.context.canvas.getBoundingClientRect();
this.mouse.x = ((event.clientX - canvasBounds.left) / (canvasBounds.right - canvasBounds.left)) * 2 - 1;
this.mouse.y = -((event.clientY - canvasBounds.top) / (canvasBounds.bottom - canvasBounds.top)) * 2 + 1;
0
votes

The most common solution for solving problems with re-sizing your browser window is adding a onWindowResize handler.

So for example:

/**
 * Resize event handler adjust renderer size and resetting camera's aspect
 */
function onWindowResize()
{
    camera.aspect = window.innerWidth / window.innerHeight;
    camera.updateProjectionMatrix();

    renderer.setSize( window.innerWidth, window.innerHeight );
}

And add the listener like this:

window.addEventListener( 'resize', onWindowResize, false );