如何调整 three.js 透视相机的视野以适应球体?

How to adjust a three.js perspective camera's field of view to fit a sphere?

我有一个球体在我的相机前面居中,其半径和距相机的距离已知。我如何调整相机的视野 (FOV) 以在任意视口尺寸内使相机准确适合球体?

Image of the angle I'm looking for

This answer 类似,但我想调整 FOV 而不是相机的距离

为了调整 FOV 以适应球体,我需要使用反三角函数来计算从到球体的距离和球体上最远的可见点形成的三角形的角度。

Image of the triangle that will give the correct angle

// to get the fov to fit the sphere into the camera
var vFOV = 2 * Math.asin(sphereRadius / distance);
// get the project's aspect ratio to calculate a horizontal fov
var aspect = this.width / this.height;
// more trig to calculate a horizontal fov, used to fit a sphere horizontally
var hFOV = 2 * Math.atan(Math.tan(vFOV / 2) / aspect);

这将以弧度给出答案。将 hFOV 或 vFOV 乘以度数 fov * (180 / Math.PI) 并应用于 camera.fov.

我最初运行陷入了使用错误三角形的陷阱。作为 this answer states "The sphere is being clipped for the same reason that if you stand close to a large sphere you can't see its "北极

不要这样做: Image of the wrong triangle for a cropped view