ThreeJS对象在视野中?

时间:2017-02-09 05:07:58

标签: javascript 3d three.js

在我的ThreeJS应用程序中,如果该对象靠近视图中心(并且对象比预定量更接近),则视图会以对象为中心摆动。我知道所有物体和观察者(相机)的纬度/经度。但是,我不知道墙上是否还有另一个物体。

有没有办法让ThreeJS告诉我这个物体是否可以从相机中看到?

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

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

Raycaster解决方案并不好,因为目标对象不是一个点,它的宽度和高度。

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

有什么建议吗?

1 个答案:

答案 0 :(得分:0)

好的,我已经编写了一个解决方案,但是如果相机无法看到它的原点,它会认为对象的视图被阻止了。批评欢迎!我希望这有助于将来的某个人。

// 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;
};