【问题标题】:ThreeJS object is in view?ThreeJS 对象在视图中?
【发布时间】:2023-03-28 05:00:02
【问题描述】:

在我的 ThreeJS 应用程序中,如果该对象靠近视图中心(并且该对象比预定的距离更近),则视图会摆动到该对象的中心。我知道所有对象和查看器(相机)的纬度/经度。不过,我不知道有没有像墙这样的其他物体。

有没有办法让 ThreeJS 告诉我该对象是否可以从相机中看到?

这个答案似乎是一个好方法,除了它对于 ThreeJS 的早期版本,我在以后的版本中找不到 webglObjects 数组的等价物:https://github.com/mrdoob/three.js/issues/3627#issuecomment-20763458

ThreeJS Frustum culling 似乎不是答案,因为它只告诉我相机是否指向正确的方向,而不是对象的视野是否被阻挡。

Raycaster 解决方案不好,因为目标对象不是一个点,而是一个点,它又宽又高。

实现我自己的遮挡剔除似乎超出了我的能力范围,除非某处有样本(我找不到)。

有什么建议吗?

【问题讨论】:

  • 您链接到的代码将无济于事。 Three.js 对其对象执行简单的平截头体剔除,它不进行手动遮挡剔除。这就是 z 缓冲区的用途。
  • 解决这个问题的一种实用方法(取决于您的确切要求)是继续研究基于 Raycaster 的解决方案:投射多条光线(不仅仅是向中心)以合理估计您的目标是否对象是否被遮挡。
  • 谢谢,这就是我要做的。我会尝试将光线从物体投射回相机(一个点)。

标签: javascript 3d three.js


【解决方案1】:

好的,我编写了一个解决方案,但需要注意的是,如果相机无法看到物体的原点,它会认为物体的视野会被阻挡。欢迎批评!我希望这对将来的某人有所帮助。

// Returns true if a named object blocks the view of the origin point of the target object
// threeScene and threeCamera are defined elsewhere as:
// threeScene = new THREE.Scene();
// threeScene.add(mesh);
// ...
// threeCamera = new THREE.PerspectiveCamera(...
// ...
var objectViewBlocked = function(objectName) {
  if (threeScene) {
    var object = threeScene.getObjectByName(objectName);
    if (object) {
      var direction = new THREE.Vector3();
      direction.subVectors(object.position, threeCamera.position); // Subtracting two vectors gives a direction vector to one from another
      direction.normalize();                                       // THREE.Raycaster() requires a normalized direction vector
      var raycaster = new THREE.Raycaster(threeCamera.position, direction);
      var intersects = raycaster.intersectObjects(threeScene.children, false); // Get list of objects that intersect the ray
      if (intersects.length > 0) {
        for (j=0; j<intersects.length; j++) {
          if ((intersects[j].object !== undefined) && (intersects[j].object['name'] !== objectName) && (intersects[j].object['name'] !== '')) {
            // Ray intersects an object other than the target object and nameless objects
            return true;
          }
        }
      }

      // The ray intersects only the target object and nameless objects (i.e. the grid on the floor, etc.) but nothing that occludes it
      return false;
    }
  }

  // Scene is null or can't get object
  return true;
};

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-05-28
    • 2014-07-22
    • 1970-01-01
    • 2013-04-06
    • 2013-10-05
    • 2019-10-21
    • 2021-04-30
    • 1970-01-01
    相关资源
    最近更新 更多