How to fit camera to model #74
Answered
by
jnsmalm
goldenratio
asked this question in
Q&A
-
Hi, How can I achieve this with camera orbit control? Any help is appreciated. |
Beta Was this translation helpful? Give feedback.
Answered by
jnsmalm
Jan 11, 2022
Replies: 1 comment 2 replies
-
Hey, First you need to calculate the bounds of the model. const getMeshBounds = (mesh) => {
let min = PIXI3D.Vec3.transformMat4(
mesh.geometry.positions.min, mesh.worldTransform.array)
let max = PIXI3D.Vec3.transformMat4(
mesh.geometry.positions.max, mesh.worldTransform.array)
for (let i = 0; i < 3; i++) {
let temp = min[i]
min[i] = Math.min(min[i], max[i])
max[i] = Math.max(temp, max[i])
}
return { min, max }
}
const getModelBounds = (model) => {
model.updateTransform()
let modelBounds = getMeshBounds(model.meshes[0])
for (let i = 1; i < model.meshes.length; i++) {
let meshBounds = getMeshBounds(model.meshes[i])
for (let j = 0; j < 3; j++) {
modelBounds.min[j] =
Math.min(modelBounds.min[j], meshBounds.min[j])
modelBounds.max[j] =
Math.max(modelBounds.max[j], meshBounds.max[j])
}
}
return modelBounds
} The we need the function which uses the bounds and calculates the distance of the camera from the object. const setDistanceToFitModel = (cameraControl, model) => {
let bounds = getModelBounds(model)
let aspect = window.innerWidth / window.innerHeight
let min = bounds.min
let max = bounds.max
let height = Math.abs(min[1]) + Math.abs(max[1])
let width = Math.abs(min[0]) + Math.abs(max[0])
let depth = Math.abs(min[2]) + Math.abs(max[2])
let fov = PIXI3D.Camera.main.fieldOfView
cameraControl.distance = height / 2 / Math.tan(Math.PI * fov / 360)
cameraControl.distance = Math.max(cameraControl.distance,
width / aspect / 2 / Math.tan(Math.PI * fov / 360))
cameraControl.distance += (max[2] + Math.abs(min[2])) / 2
cameraControl.target.x = (max[0] + min[0]) / 2
cameraControl.target.y = (max[1] + min[1]) / 2
cameraControl.target.z = (max[2] + min[2]) / 2
} I have tested with a few models, and it seems to work. |
Beta Was this translation helpful? Give feedback.
2 replies
Answer selected by
goldenratio
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Hey,
First you need to calculate the bounds of the model.