Animating lines with 3 different positions

In my project i have 2 lines.
Each line changes position when you click on the screen.
The position of each line always falls randomly in thirds of the screen width.
I accomplished the clicks and the random position in thirds.

Now i would like the lines to animate to the new position on mousePress but i don’t know how to go about it. i’m wondering if a have to rebuild in another way.

can someone guide me? :slight_smile:

1 Like

It’s not easy to get from what you had to what you needed. Here’s the working example instead:

new p5();

function windowResized() {
  resizeCanvas(windowWidth, windowHeight);

var backcolor = "rgb(194, 24, 91)";
var linecolor = "rgb(240, 98, 146)";

var targetX;
var targetY;
var currentX = 0;
var currentY = 0;

function setup(){
  createCanvas(windowWidth, windowHeight);
  currentX = targetX;
  currentY = targetY;

function draw(){
  // Adjust current to match target.
  currentX = lerp( currentX, targetX, 0.1 );
  currentY = lerp( currentY, targetY, 0.1 );
  // Redraw lines.
  line(currentX, 0 , currentX, height);
  line(0, currentY, width, currentY);

function mousePressed(){

function randomPositions(){
  var h = height;
  var w = width;
  var thirdsH = [h/3, h/2, h/1.5 ];
  var thirdsV = [w/3, w/2, w/1.5];
  targetX = random(thirdsH);
  targetY = random(thirdsV);

The main changes are that, since you’re now redrawing the line every frame, noLoop() and loop() calls are gone, and the line drawing happens in draw. Of course, the lines’ positions are also being updated. This works by having a “current” position for the line (where it is now) and a “target” position for the line (where it should try to be).

The code that sets the random target is now in its own function. That way random targets can be set both initially (in setup()) and when the user clicks (mousePressed()).

The updating of the position itself is done with a call to lerp(). You might want to look that one up in the reference if you don’t know what it does already.

Please make sure you understand how this code works before you make additional changes to it.

1 Like