Reference an Object3D by its id and transform it

Hello!
I am new to Three.js, So in my application I’ve an array which contains the ids of Object3D in the scene. I want to iterate through the array containing id’s and perform operations on each of the Object. I tried the .getObjectById(). It seems to not work. Any help is greatly appreciated!

You are either:

  1. Using wrong ids to reference objects.
  2. Updating objects in an incorrect way.
  3. Writing C++ and trying to compile it using webpack to run it within a browser.

There’s approximately 0% chance of helping you in any way, unless you’d share some code with us. :’)

1 Like

Sorry for the brevity. Also new to using forums.
(I am using Angular-TypeScript)

	objectArray.forEach(part => {
  part._node.forEach(node => {
    var objectBoundBox: THREE.Box3 = new THREE.Box3();
    var objectCenters: THREE.Vector3 = new THREE.Vector3();
    objectBoundBox.setFromObject(node);
    objectBoundBox.getCenter(objectCenters);
    var distanceToModelCentre: number = objectCenters.distanceTo(modelBoundCenter);
    distanceArray.push(distanceToModelCentre);
    //ExplodeData.set(node.id, { bboxCenter: objectCenters, distanceToCenter: distanceToModelCentre });
    ExplodeData.set(distanceToModelCentre, { id: node.id, bboxCenter: objectCenters });
  });
})
distanceArray.sort(function (a, b) { return a - b });
console.log(ExplodeData);
distanceArray.forEach(distanceFromCenter => {
  console.log(ExplodeData.get(distanceFromCenter).id);
})
var test: Object3D = new Object3D();
test.getObjectById(id);
test.translateX(0.1);

}
}

No worries. But you still didn’t show us where the id is defined and what’s its value - getObjectById will usually work fine, so it must be the id that’s causing problems.

I will try to reframe my question better. If I want to an get an Object3D by its id and apply transformations on it? How do I go about it?

If possible, may be best to give each mesh (at least these you care about) a name.

// If you load each mesh separately, you can just name them according to their own id or some config
object.name = 'primary-object';

// If you iterate, you can generate names based on the iteration
for (let i = 0; i < 50; i++) {
  object.name = `object-${i}`;
}

If my memory’s correct, Object3D.id is generated automatically by three based on the amount of objects you add to the scene (so each next object has previousId + 1.) It may not be a good idea to use Object3D.getObjectById since even a slight change of mesh order can wreck your app.

Using Object3D.getObjectByName is a bit safer, since you give these names yourself and can ensure they are consistent - regardless of the order you add objects to the scene.

1 Like