Atlassian uses cookies to improve your browsing experience, perform analytics and research, and conduct advertising. Accept all cookies to indicate that you agree to our use of cookies on your device. Atlassian cookies and tracking notice, (opens new window)
Confluence
For you

Programming
Results will update as you type.

P5js Animation-2 Answer

This content is archived.
Learn more
Aug 03, 2021
PVector     startPos = new PVector();
PVector     endPos = new PVector();
int         curTime = 0;
int         animSpeed = 5;
int         animDuration = 2000;
boolean     drawFlag=false;
boolean     animEndFlag = false;
boolean     click1 = false;

void setup()
{
  size(640, 480);
  smooth();
}

void draw()
{
  background(51);

  // 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);
  }
}

void mousePressed()
{
  if (click1 == false) {
    stroke(255, 0, 0);
    fill(255,0,0);
    drawFlag = true;
    curTime = 0;
    startPos.set(mouseX, mouseY, 0);
    endPos = startPos.get();
    click1 = true;
  } else {
    stroke(255);
    fill(255);
    endPos.set(mouseX, mouseY, 0);
    click1 = false;
  }
  println(click1);
}

void mouseMoved() {
  if (click1 == true) {
    endPos.set(mouseX, mouseY, 0);
  }
}

, multiple selections available,
{"serverDuration": 63, "requestCorrelationId": "d2613bba823a4638bf1b08b492ee2eb9"}