Sphere of starbursts

For the ring of Platonic solids, we wrote a function that repeatedly calls an ‘object construction’ function fnc. Each time fnc gets called, the object it returns gets moved into place, yielding a ring of different objects. Here, we write a function that also calls a function that builds new objects, but in this case it creates and places n objects at random points of an imaginary sphere centered on the origin and of radius rad:

function createSphereF(fnc, n, rad) {
    let root = new THREE.Object3D();
    for (let i = 0; i < n; i++) {
        let obj = fnc(i, n);
        let p = getRandomPointOnSphere(rad);
        obj.position.set(p.x, p.y, p.z);
        root.add(obj);
    }
    return root;
}

On lines 5 and 6, createSphereF generates a random point on the sphere and translates the object to that point. To illustrate, we’ll use createSphereF to place a lot of starbursts at random points on a sphere:1

Sphere of starbursts

We’ll need to supply createSphereF with a function fnc that generates starbursts. For this, we’d like to use the starburst function we wrote earlier (see the starburst page). Unfortunately, createSphereF calls function fnc with two integers i and n whereas starburst expects to receive different values, specifically, the maximum number of rays and the maximum radius of a starburst:

starburst(maxRay, maxRad)

The way around this is to build a closure for starburst that includes bindings for the two values it requires.

function makeStarburstFnc(maxRays, maxRad) {
    function fnc() {
        return starburst(maxRays, maxRad);
    }
    return fnc;
}

Then, whenever the maximum number of rays (maxRays) or the maximum radius (maxRad) changes, we simply recreate our starburst function with their new values and then pass this function to createSphereF to recreate the sphere of starbursts:

let starburstFnc = makeStarburstFnc(maxRays, maxRad)
root = createSphereF(starburstFnc, nbrBursts, sphereRadius)

Here, starburstFnc has access to the bindings it needs (maxRays and maxRad) while createSphereF has access to the those it needs (nbrBursts, sphereRadius, and the starburst-generation function itself).

  1. The three parameters in the GUI determine the number of starbursts on the sphere, the maximum radius of each starburst, and the maximum number of rays per starburst. Click Go to apply the current settings. If you’re a Star Trek fan, set all three to high values, generate the scene, and be reminded of the 1967 episode Trouble with Tribbles.