【问题标题】:ThreeJS Match GLTF Model To Size Of Bounding BoxThreeJS 将 GLTF 模型与边界框的大小匹配
【发布时间】:2021-04-13 20:33:58
【问题描述】:

我想将导入的 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 );

【问题讨论】:

  • 我会计算两个边界框每边(x,y,z)的长度,然后计算它们的商。然后使用该比率来设置比例。如果您的 glb 模型的边界框不完全是立方体,这意味着您将在轴上具有不同的比率,您需要通过对它们进行排序来使用最小或最大的比率,以将模型包含在立方体中。如果您需要代码方面的帮助,请告诉我。
  • 非常感谢,是的,我可以在代码方面使用一些帮助。我不确定如何应用您描述的方法(就像我找到的所有其他解决方案一样)。如果你能用代码告诉我如何做你描述的事情,那就太好了:)

标签: javascript three.js scale


【解决方案1】:

例如这样:

// 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);

【讨论】:

  • 好的,我会尽快尝试的。当一切都检查出来时,我会接受你的回答。这很有帮助,非常感谢!
  • 非常感谢!但要获得边界框,我必须以不同的方式进行。为了完成这项工作,我必须使用var sceneBounds = new THREE.Box3().setFromObject( cube );meshBounds = new THREE.Box3().setFromObject( model ); 模型,但除此之外,它还有效!
猜你喜欢
  • 2016-04-06
  • 1970-01-01
  • 2011-01-01
  • 1970-01-01
  • 2019-07-02
  • 1970-01-01
  • 2014-07-13
  • 1970-01-01
  • 2019-09-10
相关资源
最近更新 更多