GLTF模型与包围盒大小的匹配

本教程将介绍GLTF模型与包围盒大小的匹配的处理方法,这篇教程是从别的地方看到的,然后加了一些国外程序员的疑问与解答,希望能对你有所帮助,好了,下面开始学习吧。

GLTF模型与包围盒大小的匹配 教程 第1张

问题描述

我希望将导入的GLB模型缩放到与场景中的立方体相同的大小。需要确保模型位于阴影投射区域内,并且足够大以使阴影可见。

我已经计算了两个对象的边界框:

// shadowcasting area 
var sceneExtent = new THREE.BoxGeometry( 4, 4, 4 );
var cube = new THREE.Mesh( sceneExtent, material );
var sceneBounds = sceneExtent.computeBoundingBox()

// imported mesh
model.traverse( function ( child ) {
 if ( child.isMesh ) {
  child.geometry.computeBoundingBox()
  meshBounds = child.geometry.boundingBox
 }
} );

但现在我不知道怎么处理它们来修改GLTF模型的scale

// meshBounds = child.geometry.boundingBox
// sceneBounds = sceneExtent.computeBoundingBox()

// how to resize model scale to match size of sceneBounds

model.scale.set(1,1,1)

我已经研究了很多,但到目前为止我似乎还不明白我找到的解决方案。

怎么修改模型比例以使sceneBounds与我已有的信息相匹配?

更新:若要获取边界框,请改用.setFromObject()

sceneBounds = new THREE.Box3().setFromObject( cube );
meshBounds = new THREE.Box3().setFromObject( model );

推荐答案

例如:

// Calculate side lengths of scene (cube) bounding box
let lengthSceneBounds = {
  x: Math.abs(sceneBounds.max.x - sceneBounds.min.x),
  y: Math.abs(sceneBounds.max.y - sceneBounds.min.y),
  z: Math.abs(sceneBounds.max.z - sceneBounds.min.z),
};

// Calculate side lengths of glb-model bounding box
let lengthMeshBounds = {
  x: Math.abs(meshBounds.max.x - meshBounds.min.x),
  y: Math.abs(meshBounds.max.y - meshBounds.min.y),
  z: Math.abs(meshBounds.max.z - meshBounds.min.z),
};

// Calculate length ratios
let lengthRatios = [
  (lengthSceneBounds.x / lengthMeshBounds.x),
  (lengthSceneBounds.y / lengthMeshBounds.y),
  (lengthSceneBounds.z / lengthMeshBounds.z),
];

// Select smallest ratio in order to contain the model within the scene
let minRatio = Math.min(...lengthRatios);

// If you need some padding on the sides
let padding = 0;
minRatio -= padding;

// Use smallest ratio to scale the model
model.scale.set(minRatio, minRatio, minRatio);

好了关于GLTF模型与包围盒大小的匹配的教程就到这里就结束了,希望趣模板源码网找到的这篇技术文章能帮助到大家,更多技术教程可以在站内搜索。