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

查看:25
本文介绍了为可见的 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(D.x/D.z) 给出角度 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天全站免登陆