简体   繁体   中英

Three.js Inaccurate Raycaster

I am trying to detect clicks on my Plane mesh. I set up a raycaster using the examples as a guide.

Here is the code: http://jsfiddle.net/BAR24/o24eexo4/2/

When you click below the marker line, no click will be detected even though the click was inside the plane (marker line has no effect).

Also try resizing the screen. Then, even clicks above the marker line may not work.

Maybe this has to do with use of an orthographic camera? Or not updating some required matrix?

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

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

  raycaster.setFromCamera(mouse, camera)

  var intersects = raycaster.intersectObjects(objects);

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

Your CSS will affect your raycasting calculations. One thing you can do is set

body {
    margin: 0px;
}

For more information, see THREE.js Ray Intersect fails by adding div .

You also have to handle window resizing correctly. The typical pattern looks like this:

function onWindowResize() {

    var aspect = window.innerWidth / window.innerHeight;

    camera.left   = - frustumSize * aspect / 2;
    camera.right  =   frustumSize * aspect / 2;
    camera.top    =   frustumSize / 2;
    camera.bottom = - frustumSize / 2;

    camera.updateProjectionMatrix();

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

}

Study the three.js examples. In particular, see http://threejs.org/examples/webgl_interactive_cubes_ortho.html .

Also, read this answer , which describes how to properly instantiate an orthographic camera.

three.js r.80

Try this... It will work anywhere even you have margin and scroll!

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

      var position = $(WGL.ctx.domElement).offset(); // i'm using jquery to get position 
      var scrollUp = $(document).scrollTop();
      if (event.clientX != undefined) {
           mouse.x = ((event.clientX - position.left) / WGL.ctx.domElement.clientWidth) * 2 - 1;
           mouse.y = - ((event.clientY - position.top + scrollUp) / WGL.ctx.domElement.clientHeight) * 2 + 1;
      } else {
           mouse.x = ((event.originalEvent.touches[0].pageX - position.left) / WGL.ctx.domElement.clientWidth) * 2 - 1;
           mouse.y = - ((event.originalEvent.touches[0].pageY + position.top - scrollUp) / WGL.ctx.domElement.clientHeight) * 2 + 1;
      }

      raycaster.setFromCamera(mouse, camera)
      var intersects = raycaster.intersectObjects(objects);  
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM