调整相机以获得可见的Three.js形状 [英] Adjusting camera for visible Three.js shape

查看:337
本文介绍了调整相机以获得可见的Three.js形状的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个相机正在观看的CubeGeometry,我希望相机可以放大,以便立方体完全可见,但不会更大。

I have a CubeGeometry which the camera is looking at, and I want the camera to zoom so that the cube is entirely visible, but no larger.

我的初始尝试将立方体顶点转换为相机坐标系,

My initial attempt was to convert the cube verticies to the camera coordinate system,

function toScreenXY(position, camera) {
  var pos = position.clone();
  var projScreenMat = new THREE.Matrix4();
  projScreenMat.multiply(camera.projectionMatrix, camera.matrixWorldInverse);
  projScreenMat.multiplyVector3( pos );

  return pos;
}
function ScaleInView() {
  camera.fov = 0.0;
  for (var i=0; i<8; i++) {
    proj2d = toScreenXY(cube.geometry.vertices[i],camera);
    angle = 57.296 * Math.max(Math.atan(proj2d.x/proj2d.z), Math.atan(proj2d.y/proj2d.z));
    camera.fov = Math.max(camera.fov,angle);
  }
  camera.updateProjectionMatrix();
}

我认为这样可行,但有时它太小了,有时也是大(取决于相机的位置)。

I thought this would work, but sometimes it's too small, and other times too large (depending on the position of the camera).

我还需要为正射相机执行此操作。

I also need to do this for Orthographic Camera.

编辑:
我知道当立方体面向相机时如何做到这一点,我正在寻找一种方法来做到这一点,当相机被移动到一些任意(r,theta) ,phi)位置(球面极坐标; r实际上是我的目的)。

I know how to do this when the cube is facing the camera, I'm looking for a way to do it when the camera is moved to some arbitrary (r, theta, phi) position (spherical polar coordinates; r is actually constant for my purposes).

推荐答案

乘以camera.matrixWorldInverse给出一个矢量在相机的坐标中,但重要的是不应用透视。

Multiplying by camera.matrixWorldInverse gives a vector in the camera's coordinates, but importantly does not apply perspective.

function toCameraCoords(position) {
  return camera.matrixWorldInverse.multiplyVector3(position.clone());
}

然后我们可以找到最适合所有角落的角度现场。 arctan(Dx / Dz)给出角度BCD,其中B是摄像机正在看的东西,C是摄像机的位置,D是想要在摄像机坐标中可见的物体的位置。

We can then find the smallest angle that will fit all the box corners in the scene. arctan(D.x / D.z) gives the angle BCD where B is what the camera is looking at, C is the camera's position, and D the position of an object that you want to be visible in the camera coordinates.

在我的情况下,以下内容确保多维数据集边框完全可见。

In my case, the following ensures that the the cube boundbox is fully visible.

function ScaleInView() {
  var tmp_fov = 0.0;

  for (var i=0; i<8; i++) {
    proj2d = toCameraCoords(boundbox.geometry.vertices[i]);

    angle = 114.59 * Math.max( // 2 * (Pi / 180)
      Math.abs(Math.atan(proj2d.x/proj2d.z) / camera.aspect),
      Math.abs(Math.atan(proj2d.y/proj2d.z))
    );
    tmp_fov = Math.max(tmp_fov, angle);
 }

 camera.fov = tmp_fov + 5; // An extra 5 degrees keeps all lines visible
 camera.updateProjectionMatrix();
}

这篇关于调整相机以获得可见的Three.js形状的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆