3

I loaded some objects via OBJLoader , loaded object contain one parent and multiple childs; then I apply Raycaster and find clicked child.

Then I want to update position of child object, but initial position comes zero for all childs.

var intersect = intersects[0].object;
intersect.position.y = intersect.position.y + 5; // 0 + 5 

But in my scene all looks fine. Also, If i remove clicked object, actually it is removed from scene. I think I missed some point their positions cant be (0,0,0). How can I reach their relative position ?

ubaltaci
  • 1,016
  • 1
  • 16
  • 27

4 Answers4

3

Try this, then read position(). I had the same issue, got an answer here. (geom is your Meshes geometry.)

objMesh.centroid = new THREE.Vector3();
for (var i = 0, l = geom.vertices.length; i < l; i++) {
  objMesh.centroid.add(geom.vertices[i].clone());
}
objMesh.centroid.divideScalar(geom.vertices.length);
var offset = objMesh.centroid.clone();

objMesh.geometry.applyMatrix(new THREE.Matrix4().makeTranslation(-offset.x, -offset.y, -offset.z));

objMesh.position.copy(objMesh.centroid);
Gangula
  • 5,193
  • 4
  • 30
  • 59
Tezcan
  • 690
  • 2
  • 6
  • 16
  • :) I must admit that I didnt believe first but it works. Then Can we say it's a three.js bug ? Since relative position must be computed before, but now we are computing manually. – ubaltaci Jan 24 '13 at 21:24
  • No, as i learned before, this is about heart of 3D :) Position Of Objects are relative to theirselves. – Tezcan Jan 25 '13 at 09:54
3

Here is code for set Transform Control into center of object:

let objLoader = new THREE.OBJLoader();
let mtlLoader = new THREE.MTLLoader();
mtlLoader.load("path/to/mtlFile.mtl", (materials) => {
  materials.preload();
  objLoader.setMaterials(materials).load("path/to/objFile.obj", (object3d) => {
    object3d.traverse((child) => {
      if (child instanceof THREE.Mesh) {
        child.geometry.computeBoundingBox();
        let matrix = new THREE.Vector3();
        let offset = child.geometry.boundingBox.getCenter(matrix);
        child.geometry.applyMatrix(new THREE.Matrix4().makeTranslation(-offset.x, -offset.y, -offset.z));
        child.position.copy(offset);
        objects.push(child);
      }
    });
    scene.add(object3d);
  });
});
Gangula
  • 5,193
  • 4
  • 30
  • 59
2

The position is relative to the parent

Multiply the position by the transform of the parent to get the world-space coordinates, if that's what you're seeking

bjorke
  • 3,295
  • 1
  • 16
  • 20
  • 1
    I know there is relativiness. But no matter what the children locations' are , their positions are always 0,0,0. – ubaltaci Jan 24 '13 at 14:42
1

That is because all objects in a obj file have their pivot at World 0,0,0 no matter where their local pivot was before exporting.

derWowa
  • 11
  • 1