Get center point of all enabled mesh instances / models / entities

Hey everyone,

I’d like to maintain a center pivot point based on any loaded entities in my scene. I’ve tried looking at the docs, forums, etc., but I’m not finding any answers.

I’m quite comfortable using Javascript and the PlayCanvas object. I just can’t find either the reference or the right method to request all active “elements” in my scene.

If there is a function I can call which simply calculates the center point of everything in one’s scene that would be great as well.

Much appreciation,
Bob

You can use a method like this, which is included in the Model Viewer template as well:

MyScript.prototype.calculateAabb = function (entity, modelsAdded) {
    var i = 0;
    
    if (entity.model) {
        var mi = entity.model.meshInstances;
        for (i = 0; i < mi.length; i++) {
            if (modelsAdded === 0) {
                this.bounding.copy(mi[i].aabb);
            } else {
                this.bounding.add(mi[i].aabb);
            }

            modelsAdded += 1;
        }
    }

    for (i = 0; i < entity.children.length; ++i) {
        modelsAdded += this.calculateAabb(entity.children[i], modelsAdded);            
    }

    return modelsAdded;
};

And use it like this:

this.bounding = new pc.BoundingBox();
this.calculateAabb(parentEntity);

// the bounding box center would be the total volume center point
console.log(this.bounding.center);
1 Like

Thanks. Leonidas. I’ll try this out in a little bit here.

1 Like