I'm trying to determine how far away the camera needs to be from my object3D which is a collection of meshes in order for the entire model to be framed in the viewport.
I get the object3D size like this:
public getObjectSize ( target: THREE.Object3D ): Size {
let box: THREE.Box3 = new THREE.Box3().setFromObject(target);
let size: Size = {
depth: (-1 * box.min.z) + box.max.z,
height: (-1 * box.min.y) + box.max.y,
width: (-1 * box.min.x) + box.max.x
};
return size;
}
Next I use trig in an attempt to determine how far back the camera needs to be based on that box size in order for the entire box to be visible.
private determinCameraDistance(): number {
let cameraDistance: number;
let halfFOVInRadians: number = this.geometryService.getRadians(this.FOV / 2);
let height: number = this.productModelSizeService.getObjectSize(this.viewService.primaryView.scene).height;
let width: number = this.productModelSizeService.getObjectSize(this.viewService.primaryView.scene).width;
cameraDistance = ((width / 2) / Math.tan(halfHorizontalFOVInRadians));
return cameraDistance;
}
The math all works out on paper and the length of the adjacent side of the triangle (the camera distance) can be verified using a^2 + b^2 = c^2. However for some reason the distance returned is 10.4204 while the camera distance I need to show the entire object3D is actually 95 (determined by hard coding the value) which results in only being able to see a tiny portion of my model.
Any ideas on what I might be doing wrong, or better way to determine this. It seems to me like there is some kind of unit conversion that I'm missing when going from the box sizing units to camera distance units
Actual numbers used in the calculation:
FOV = 110 degrees,
Object3D size: {
Depth: 11.6224,
Height: 18.4,
Width: 29.7638
}
So we take half the field of view to create a right triangle with the adjacent side placed along our camera distance, that's 55 degrees. We then use the formula Degrees * PI / 180
to convert 55 degrees into the radian equivalent, which is .9599. Next we take half the object3D width, again to create a right triangle, which is 14.8819. We can now take our half width and divide it by the tangent of the FOV (in radians), this gives us the length for the adjacent side / camera distance of 10.4204.
We can further verify this is the correct length of this side I'll get the length of the hypotenuse using SOHCAHTOA again:
Sin(55) = 14.8819 / y
.8192 * y = 14.8819
y = 14.8819 / .8192
y = 18.1664
Now using this we can use the pythagorean theorem solve for b to check our math.
14.8819^2 + b^2 = 18.1664^2
221.4709 + b^2 = 330.0018
b^2 = 108.5835
b = 10.4203 (we're off by .0001 but that's due to rounding)