Demo of Dynamic Entities with Collision, Rigidbody, and random Color

I just wanted to share a small demo incase it may be of some use to others. The demo starts with one fixed box, then randomly creates 100 hexahedron’s (Hexahedron - Wikipedia) of random sizes. I had to look up that word because the objects created are not all cubes :smiley:

Hopefully I’m doing this right. Below is the link to the public project, and a link to a release for quick viewing:

A few notable words about this demo include:

   Objects are created dynamically
   Random diffuse color is assigned
   Collision, and Rigidbody are added dynamically
   Objects are created with restitution of 1, and when in contact with each other demonstrate an elastic collision (bouncy)
   Ground has restitution, and friction of 0.5, which gradually brings the objects to rest
   Ground plane collision box only covers half the total area, and objects may bounce off to oblivion
   Fixed camera. No support for moving about.

The important part of the code is shown below, mainly because I’m not sure how long it will be available for:

        SpawnEntity: function () {
            if(!this.entityNode || this.spawnedEntities >= this.maxEntities) {
            var cube = new pc.Entity();
   = 'cube-' + Math.random().toFixed(4);
            cube.addComponent('model', { type: 'box', castShadows: true, receiveShadows: true });
            var a = this.RandomFloat(0.1, 1.0);
            var r = this.RandomFloat(0.05, 1.0);
            var g = this.RandomFloat(0.05, 1.0);
            var b = this.RandomFloat(0.05, 1.0);
            var material = app.assets.getAssetById(this.material).resource.clone();
            material.diffuse.a = a;
            material.diffuse.r = r;
            material.diffuse.g = g;
            material.diffuse.b = b;
            cube.model.model.meshInstances[0].material = material;
            var px = this.RandomFloat(-20.0, 20.0);
            var py = this.RandomFloat(8.5, 35.5);
            var pz = this.RandomFloat(-20.0, 20.0);
            cube.setPosition(px, py, pz);
            var sx = this.RandomFloat(2.5, 4.5);
            var sy = this.RandomFloat(2.5, 4.5);
            var sz = this.RandomFloat(2.5, 4.5);
            cube.setLocalScale(sx, sy, sz);
            cube.addComponent('collision', { type: 'box', halfExtents: new pc.Vec3(sx * 0.5, sy * 0.5, sz * 0.5) });
            cube.addComponent('rigidbody', { type: 'dynamic', mass: 1.0, enabled: true, restitution: 1.0 });
        RandomFloat: function (min, max) {
            return Math.random() * (max - min) + min;
        RandomInteger: function (min, max) {
            return Math.floor(Math.random() * (max - min + 1)) + min;

TY r2d2… but as a graphic artist : What the heck are those lines ! ahahah! :slight_smile: my brain is really no coder!

Thanks for this, answered some of my questions when playing with playcanvas today