Three.js基于内部网格设置Object3D的中心

时间:2014-05-29 05:30:47

标签: three.js

当我得到它们不在对象中心的顶点时,我有一个在Object3D中的网格集。所以我需要计算object3D的中心然后移动网格以使它们与中心对齐。我试过计算每个Mesh的边界框然后max - min / 2;这不起作用。这里的任何帮助都会很棒。我试过了Object3D.setFromObject();这只会返回无限。

2 个答案:

答案 0 :(得分:1)

为了使Object3D居中,根据它的子节点,你必须迭代它们,据我所知。代码如下所示:

// myObject3D is your Object3D

var children = myObject3D.children,
  completeBoundingBox = new THREE.Box3(); // create a new box which will contain the entire values

for(var i = 0, j = children.length; i < j; i++){ // iterate through the children

  children[i].geometry.computeBoundingBox(); // compute the bounding box of the the meshes geometry

  var box = children[i].geometry.boundingBox.clone(); // clone the calculated bounding box, because we have to translate it

  box.translate(children[i].position); // translate the geometries bounding box by the meshes position

  completeBoundingBox.addPoint(box.max).addPoint(box.min); // add the max and min values to your completeBoundingBox

}

var objectCenter = completeBoundingBox.center()

console.log('This is the center of your Object3D:', objectCenter );

// You want the center of you bounding box to be at 0|0|0

myObject3D.position.x -= objectCenter.x;
myObject3D.position.y -= objectCenter.y;
myObject3D.position.z -= objectCenter.z;

希望我理解你的问题吧!

答案 1 :(得分:1)

center = function(obj) {
  var children = obj.children,
  completeBoundingBox = new THREE.Box3();
  for(var i = 0, j = children.length; i < j; i++) {
    children[i].geometry.computeBoundingBox();
    var box = children[i].geometry.boundingBox.clone();
    box.translate(children[i].position);
    completeBoundingBox.set(box.max, box.min);
  }
  var objectCenter = completeBoundingBox.center()
  console.log('This is the center of your Object3D:', objectCenter );
  obj.position.x -= objectCenter.x;
  obj.position.y -= objectCenter.y;
  obj.position.z -= objectCenter.z;
}