Animation Solution with objects


Main Code:

boolean     click1 = false;
ArrayList<Animator> myAnimators;
int count;
void setup()
{
  size(640, 480);
  smooth();
  stroke(200);
  fill(255);
  myAnimators = new ArrayList<Animator>();
}

void draw()
{


  background(51);
  for(int i = 0; i<myAnimators.size();i++) {
    myAnimators.get(i).drawAnimator();
  }
  
// count++;
//if (count >= 15) {
// myAnimators.add(new Animator(floor(random(0,width)), floor(random(0,height))));
// myAnimators.get(myAnimators.size()-1).endClick(floor(random(0,width)), floor(random(0,height)));
// count = 0;
//}

}

void mousePressed()
{
  if (click1 == false) {
    myAnimators.add(new Animator(mouseX, mouseY));
    click1 = true;
  } else {
    myAnimators.get(myAnimators.size()-1).endClick(mouseX, mouseY); 
    click1 = false;
  }
  println(click1);
}

void mouseMoved() {
  if (click1 == true) {
   myAnimators.get(myAnimators.size()-1).endPos.set(mouseX, mouseY);
  }
}


Class code:

class Animator {
  PVector     startPos = new PVector();
  PVector     endPos = new PVector();
  int         curTime = 0;
  int         animSpeed = 5;
  int         animDuration = 2000;
  boolean     drawFlag=false;
  boolean     animEndFlag = false;


  Animator(int X, int Y) {

    drawFlag = true;
    curTime = 0;
    startPos.set(X, Y, 0);
    endPos = startPos.get();

  }

  void endClick(int X, int Y) {
    endPos.set(X, Y, 0);
  }

  void drawAnimator() {
    // calc. the anim time

    if (curTime >= animDuration) {
      animEndFlag = true;
    }

    if (curTime <= 0) {
      animEndFlag = false;
    }

    if (animEndFlag) {
      curTime -= animSpeed;
    } else {
      curTime += animSpeed;
    }

    // calc. the proportion of completion in the animation
    float normTime = curTime * 1.0 / animDuration;

    if (drawFlag)
    {

      line(startPos.x, startPos.y, 
        endPos.x, endPos.y);

      // calculate the position of the circle on the line
      PVector dir = PVector.sub(endPos, startPos);

      PVector pos = PVector.add( startPos, PVector.mult(dir, normTime));
      ellipse(pos.x, pos.y, 20, 20);
    }
  }
}