diff --git a/examples/growth.js b/examples/growth.js index 8a730da6c1..8bd49d92c5 100644 --- a/examples/growth.js +++ b/examples/growth.js @@ -8,40 +8,87 @@ // See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // var RADIUS = 5; -var LIFETIME = 6000; +var LIFETIME = 60; // only keep these entities around for a minute + +var SIZE = 1; // starting size +var SIZE_MAX = 3; +var SIZE_MIN = 0.5; -var size = 1; var center = MyAvatar.position; var positions = [ Vec3.sum(center, Vec3.multiply(RADIUS, Vec3.FRONT)), Vec3.sum(center, Vec3.multiply(-RADIUS, Vec3.FRONT)), Vec3.sum(center, Vec3.multiply(RADIUS, Vec3.RIGHT)), Vec3.sum(center, Vec3.multiply(-RADIUS, Vec3.RIGHT)), - Vec3.sum(center, Vec3.multiply(RADIUS, Vec3.UP)), - Vec3.sum(center, Vec3.multiply(-RADIUS, Vec3.UP)), ]; +// Create spheres around the avatar var spheres = map(positions, getSphere); -Script.update.connect(function(delta) { - size += delta; // grow by 1 unit/s - each(spheres, function(sphere) { - Entities.editEntity(sphere, { dimensions: getDimensions(size) }); - }); +// Toggle sphere growth +each(spheres, function(sphere) { + var state = { + size: SIZE, + grow: true, // grow/shrink + state: false, // mutate/pause + }; + + // Grow or shrink on click + Script.addEventHandler(sphere, 'clickReleaseOnEntity', toggleGrowth); + // TODO: Toggle on collisions as well + + function toggleGrowth() { + if (state.state) { + stop(); + } else { + start(); + } + } + + function start() { + var verb = state.grow ? 'grow' : 'shrink'; + print('starting to '+verb+' '+sphere); + + Script.update.connect(grow); + state.state = true; + } + + function stop() { + print('stopping '+sphere); + + Script.update.disconnect(grow); + state.state = false; + state.grow = !state.grow; + } + + function grow(delta) { + if ((state.grow && state.size > SIZE_MAX) || // cannot grow more + (!state.grow && state.size < SIZE_MIN)) { // cannot shrink more + stop(); + return; + } + + state.size += (state.grow ? 1 : -1) * delta; // grow/shrink + Entities.editEntity(sphere, { dimensions: getDimensions(state.size) }); + } }); -Script.scriptEnding.connect(function() { + +Script.scriptEnding.connect(function() { // cleanup each(spheres, function(sphere) { Entities.deleteEntity(sphere); }); }); +// NOTE: Everything below this line is a helper. +// The basic logic of this example is entirely above this note. + // Entity helpers function getSphere(position) { return Entities.addEntity({ type: 'Sphere', position: position, - dimensions: getDimensions(size), + dimensions: getDimensions(SIZE), color: getColor(), gravity: Vec3.ZERO, lifetime: LIFETIME,