How do I Visualize a Bounding Box as an Render Entity?

I’m trying to create a rendered entity that is the exact dimensions and rotations as the bounding box of an object in real time, but it seems almost impossible to achieve.

Basically, a visualization of the AABB but as a rendered entity.

Has anyone done this before?

Thanks

Hi @Grimmy,

I haven’t tackled this before, but I gave it a go. Here is the complete script and an example project using it:

var BoundingToCube = pc.createScript('boundingToCube');

// initialize code called once per entity
BoundingToCube.prototype.initialize = function () {

    // --- find all mesh instances
    let meshInstances = [];
    const renders = this.entity.findComponents('render');
    renders.forEach(render => {
        meshInstances = meshInstances.concat(render.meshInstances);
    });

    // --- calculate the total bounding box
    const bounding = new pc.BoundingBox();

    meshInstances.forEach((meshInstance, index) => {

        if (index === 0) {
            bounding.copy(meshInstance.aabb);
        } else {
            bounding.add(meshInstance.aabb);
        }
    });

    // --- add a cube to match the bounding box
    const cube = new pc.Entity();
    cube.addComponent('render', {
        type: 'box'
    });
    this.app.root.addChild(cube);

    cube.setPosition(bounding.center);
    cube.setLocalScale(bounding.halfExtents.mulScalar(2));
};

https://playcanvas.com/editor/scene/1757943

2 Likes

Perfect! Thank You so much for this! I was almost there myself but you made the code much more succinct than mine :slight_smile:

1 Like