4

I have a code that performs animation. a sphere moves from the beginning of a line to the end of the line. When starts again ends the motion again. starts from the first vertex and ends at the last vertex of the line. I want to put 20 or so spheres, doing the same animation, but at the same time and in the same distance. How can I do it?

this is my code:

var vertices = mesh.geometry.vertices;
var duration = 10;

function startToEnd() {
    var i = 0;
    async.eachSeries(vertices, function(vertice, callback) {
        if (i !== 0) {
            sphere.position.copy(vertices[i - 1]);
            new TWEEN.Tween(sphere.position).to(vertices[i],  duration).delay(duration).onComplete(function() {
                callback(null);
            }).start();
        } else {
            callback(null);
        }
        i++;
    }, startToEnd);
}
startToEnd();

this image is a example.. enter image description here

this is result of my code enter image description here

leroydev
  • 2,915
  • 17
  • 31
yavg
  • 2,761
  • 7
  • 45
  • 115

1 Answers1

2

I got something that I think is pretty close to what you want:

var vertices = mesh.geometry.vertices;
var duration = 20;
var spheres = [];
var amountOfSpheres = 20;

for (var i = 0; i < amountOfSpheres; i++) {
  spheres.push(new THREE.Sprite(rttMaterial));
  scene.add(spheres[i]);
}

function endlessArrayIndex(index, arrayLength) {
    if (index >= arrayLength) {
    return index % arrayLength;
  }
  return index;
}

function startToEnd() {
  i = 0;
  async.each(spheres, function(sphere, cb1) {
    var j = 0;
    var verticeIndex = endlessArrayIndex(i * Math.round(vertices.length / amountOfSpheres), vertices.length);
    async.eachSeries(vertices, function(vertice, cb2) {
      if (verticeIndex !== 0) {
        var verticeToCopy = vertices[verticeIndex - 1];
        sphere.position.copy(verticeToCopy);
        new TWEEN.Tween(sphere.position).to(vertices[verticeIndex], duration).delay(duration).onComplete(function() {
          cb2(null);
        }).start();
      } else {
        cb2(null);
      }
      verticeIndex = endlessArrayIndex(verticeIndex + 1, vertices.length);
    }, cb1);
    i++;
  }, startToEnd);
}
startToEnd();

Result of the above code:

Sphere movement result from the code above

leroydev
  • 2,915
  • 17
  • 31
  • friend, thank you're a genius. in theory it works as I want. the only problem is that the distance between each sphere is not the same. What should be done to fix it? – yavg Dec 16 '15 at 14:06
  • @yavg I updated my answer with a better way of calculating distance between spheres. – leroydev Dec 16 '15 at 14:19
  • excellent, you're the smartest person I've seen in this community, and maybe in my life !. Thank you! – yavg Dec 16 '15 at 14:33