I am trying to create a bounding box mesh that updates its bounding box whenever it receives a new child mesh so that the bounding box includes all the children meshes. I am finding this hard to do with the typical observers and functions because onAfterWorldMatrixUpdate will trigger when you call getHierarchyBoundingVectors() causing an infinite loop.
Is there a better way to listen for changes to a node/mesh scene graph hierarchy?
let container = new Mesh(name, scene);
let { min, max } = container.getHierarchyBoundingVectors();
container.setBoundingInfo(new BoundingInfo(min, max));
container.onAfterWorldMatrixUpdateObservable.add((v) => {
let { min, max } = container.getHierarchyBoundingVectors(); //triggers observable causing infinite loop
container.setBoundingInfo(new BoundingInfo(min, max));
})
let sphere = new MeshBuilder.CreateSphere()
sphere.setParent(container)
But it won’t work in your case because onAfterWorldMatrixUpdateObservable is called on the container before the parent property of the sphere is updated.
You can delay the execution of onAfterWorldMatrixUpdateObservable to the end of the frame, to let the code that set the parenting run:
There is a strange behavior with this approach where if you move the parent mesh the bounding box seems to drift from the child meshes, not sure whats causing this.