I want to scale the imported GLB Model to the same size a cube in my scene. It is needed to make sure that the model stays inside the shadow casting areas and is big enough to make the shadows visible.
I ‘ve calculated the bounding Boxes of both objects already:
JavaScript
x
5
1
// shadowcasting area
2
var sceneExtent = new THREE.BoxGeometry( 4, 4, 4 );
3
var cube = new THREE.Mesh( sceneExtent, material );
4
var sceneBounds = sceneExtent.computeBoundingBox()
5
and
JavaScript
1
8
1
// imported mesh
2
model.traverse( function ( child ) {
3
if ( child.isMesh ) {
4
child.geometry.computeBoundingBox()
5
meshBounds = child.geometry.boundingBox
6
}
7
} );
8
but now I do not know what to do with them to modify the scale
of the GLTF Model
JavaScript
1
7
1
// meshBounds = child.geometry.boundingBox
2
// sceneBounds = sceneExtent.computeBoundingBox()
3
4
// how to resize model scale to match size of sceneBounds
5
6
model.scale.set(1,1,1)
7
I’ve already researched quite a bit but I do not seem to understand the solutions I’ve found so far.
How can I modify the model scale to match the sceneBounds
with the information I have?
UPDATE: To get the bounding box use .setFromObject()
instead:
JavaScript
1
3
1
sceneBounds = new THREE.Box3().setFromObject( cube );
2
meshBounds = new THREE.Box3().setFromObject( model );
3
Advertisement
Answer
For example like this:
JavaScript
1
31
31
1
// Calculate side lengths of scene (cube) bounding box
2
let lengthSceneBounds = {
3
x: Math.abs(sceneBounds.max.x - sceneBounds.min.x),
4
y: Math.abs(sceneBounds.max.y - sceneBounds.min.y),
5
z: Math.abs(sceneBounds.max.z - sceneBounds.min.z),
6
};
7
8
// Calculate side lengths of glb-model bounding box
9
let lengthMeshBounds = {
10
x: Math.abs(meshBounds.max.x - meshBounds.min.x),
11
y: Math.abs(meshBounds.max.y - meshBounds.min.y),
12
z: Math.abs(meshBounds.max.z - meshBounds.min.z),
13
};
14
15
// Calculate length ratios
16
let lengthRatios = [
17
(lengthSceneBounds.x / lengthMeshBounds.x),
18
(lengthSceneBounds.y / lengthMeshBounds.y),
19
(lengthSceneBounds.z / lengthMeshBounds.z),
20
];
21
22
// Select smallest ratio in order to contain the model within the scene
23
let minRatio = Math.min(lengthRatios);
24
25
// If you need some padding on the sides
26
let padding = 0;
27
minRatio -= padding;
28
29
// Use smallest ratio to scale the model
30
model.scale.set(minRatio, minRatio, minRatio);
31