Bri
Bri

Reputation: 39

How to get P5JS line to slide to new position on function mousePressed()

I'm trying to make a jukebox animation using line as the records. I want

line(record1X1, 120, record1X2, 120);

to slide from (50, 120, 170, 120) to (375, 120, 475, 120) in my p5js sketch. I got it to work by putting

if (record1X2 < 475 && record1X1 < 375 ) {

    record1X1 += recordSpeed;

    record1X2 += recordSpeed;
}

(recordSpeed is equal to 2)

in function draw(), but I want the animation to happen on function mousePressed() on an ellipse in my drawing. I tried to use a for loop in mousePressed() to get it to work, but it just makes the line jump into place instead of having a smooth transition. Please help me.

Upvotes: 0

Views: 61

Answers (1)

Kevin Workman
Kevin Workman

Reputation: 42176

A for loop inside the mousePressed() function won't work because only the last frame will show up. Instead, you need to do all your movement inside the draw() function.

You could do something like set a boolean variable inside the mousePressed() function, which you then use inside the draw() function. Something like this:

function draw(){
  if(mouseWasPressed){
    if (record1X2 < 475 && record1X1 < 375 ) {

      record1X1 += recordSpeed;

      record1X2 += recordSpeed;
    }
  }
}

Upvotes: 1

Related Questions