4

In I have an animation of 3 characters on an ongoing loop, but I want them to go to their origin positions after, let's say, 5 seconds.

I'd also like to make them return to their initial position by pressing a key no matter how much time has passed. I'm very new to this and don't really know how to do that. This is the link to the full program. Any ideas? Thanks in advance!

var Ax = canvasW/2 - 125,
    Ay = canvasH/2;
var speedAx = 5,
    speedAy = 6;

var Bx = canvasW/2,
    By = canvasH/2;
var speedBx = 6;

var Cx = canvasW/2 + 125,
    Cy = canvasH/2;
var Cy1 = 50,
    Cy2 = canvasH - 50;
var t = 0;
var startTime = 0;
var interval = 400; // miliseconds


function setup() {
  createCanvas(canvasW, canvasH);
  
  textAlign(CENTER, CENTER);
  textFont('Fredoka One');
  
  abcSize = 150;
  
}


function draw() {

  textSize(abcSize);
  text('A', Ax, Ay);
  Ax = Ax + speedAx;
  Ay = Ay + speedAy;
  
  if(Ax<abcSize/2 || Ax>width-abcSize/2){
    speedAx*=-1
  }
  if(Ay<abcSize/2 || Ay>height- abcSize/2){
    speedAy*=-1
  }

  
  fill('magenta');
  text('B', Bx, By);
  
  Bx = Bx + speedBx 
  
  if (Bx > canvasW-45) { 
    speedBx = -speedBx;
  }
  
  if (Bx < 0+45) { 
    speedBx = speedBx * -1;
  }
  
  
  fill('yellow');
  textSize(150);
  text('C', Cx, Cy);
  
  t = map(millis(), startTime, startTime + interval, 0.0, 1.0);
  t = constrain (t, 0, 1);
  
  Cy = Cy1 * (1 - t) + Cy2 * t;
  
  if (t >= 1) {
    t = 0;
    startTime = millis();
    //  update Cx1 and Cx2 here with new values from an array
    Cy1 = Cy2;
    Cy2 = random(100, 500);
  }
}
phentnil
  • 2,195
  • 2
  • 14
  • 22
asdfg1234
  • 41
  • 1

1 Answers1

1

It seems that you have already figured out how to make the characters return to their original positions after 5 seconds based on the link. You can use the function keyPressed() to detect keypresses. Read more here. Using the keyPressed() function, you can add

function keyPressed() {
  Ax = canvasW / 2 - 125;
  Ay = canvasH / 2;
  Bx = canvasW / 2;
  By = canvasH / 2;
  Cx = canvasW / 2 + 125;
  Cy = canvasH / 2;
  resetTime = millis();
}

at the end of your code to reset the characters' positions on a keypress.

0mlml
  • 142
  • 8