在Three.js中使用正交摄影机进行不精确的光线投射

时间:2019-05-28 19:44:13

标签: javascript three.js raycasting orthographic

我正在使用three.js库开发CAD图纸的二维查看器,对于这个项目,我需要能够单击场景中的对象以进行一些操作。

使用正交摄影机对Three.js进行光线投射并不像我期望的那样精确。

这里的代码和小提琴正好显示了我的意思 https://jsfiddle.net/toriphes/a0o7td1u/

var camera, scene, renderer, square, raycaster;
init();
animate();

function init() {

  output = document.getElementById('output');

  raycaster = new THREE.Raycaster();
  // Renderer.
  renderer = new THREE.WebGLRenderer();
  //renderer.setPixelRatio(window.devicePixelRatio);
  renderer.setSize(window.innerWidth, window.innerHeight);
  // Add renderer to page
  document.body.appendChild(renderer.domElement);

  // Create camera.
  var aspect = window.innerWidth / window.innerHeight;
  var d = 20;
  camera = new THREE.OrthographicCamera(-window.innerWidth / 2, window.innerWidth / 2, window.innerHeight / 2, -window.innerHeight / 2, 1, 1000);
  camera.position.z = 10;
  camera.position.x = 25;
  camera.position.y = 25;
  camera.zoom = 10
  camera.updateProjectionMatrix()

  controls = new THREE.OrbitControls(camera, renderer.domElement);
  controls.enableRotate = false
  controls.target.x = camera.position.x;
  controls.target.y = camera.position.y;

  controls.update();


  // Create scene.
  scene = new THREE.Scene();

  var points = [
    new THREE.Vector2(10, 10),
    new THREE.Vector2(40, 10),
    new THREE.Vector2(40, 40),
    new THREE.Vector2(10, 40),
    new THREE.Vector2(10, 10)
  ]

  var shape = new THREE.Shape(points);

  var geometry = new THREE.Geometry().setFromPoints(points);

  var square = new THREE.Line(geometry, new THREE.LineBasicMaterial({
    color: 0xFF0000
  }));
  scene.add(square)

  document.addEventListener('mousemove', findIntersections, false);
}

function animate() {
  requestAnimationFrame(animate);
  renderer.render(scene, camera);
}

function updateMousePosition(event) {
  return new THREE.Vector3(
    (event.clientX - renderer.domElement.offsetLeft) /
    renderer.domElement.clientWidth *
    2 -
    1,
    -(
      (event.clientY - renderer.domElement.offsetTop) /
      renderer.domElement.clientHeight
    ) *
    2 +
    1,
    0
  );
}

function findIntersections(e) {
  var mouseposition = updateMousePosition(e);
  raycaster.setFromCamera(mouseposition, camera);
  const intersects = raycaster.intersectObjects(scene.children);
  output.innerHTML = intersects.length > 0 ?
    'Intersect: TRUE' :
    'Intersect: FALSE';
}

如果将鼠标移到红色方块附近,您会看到相交会在悬停边缘之前触发。

我在做什么错了?

1 个答案:

答案 0 :(得分:2)

线的相交检测取决于.linePrecisionRaycaster属性。

例如

raycaster.linePrecision = 0.1;
const intersects = raycaster.intersectObjects(scene.children);

必须根据场景的比例设置参数。值0.1是一个经验值,可以为您的示例提供良好的结果。遗憾的是,文档中没有提供进一步的信息(也许我忽略了某些内容,但没有找到)。