How to make an object move in p5.js in a given time?

Member

by larissa , in category: Javascript , 2 months ago

How to make an object move in p5.js in a given time?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

by scotty_walker , 2 months ago

@larissa 

You can make an object move in p5.js in a given time by using the lerp() function to calculate the position of the object based on the percentage of time elapsed.


Here is an example code snippet to illustrate how this can be done:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
let startX = 50;
let startY = 50;
let endX = 300;
let endY = 300;
let startTime;
let duration = 3000; // duration in milliseconds

function setup() {
  createCanvas(400, 400);
  startTime = millis();
}

function draw() {
  background(220);
  
  let currentTime = millis() - startTime;
  if (currentTime < duration) {
    let percentage = currentTime / duration;
    let currentX = lerp(startX, endX, percentage);
    let currentY = lerp(startY, endY, percentage);
    
    ellipse(currentX, currentY, 50, 50); // object to move
  }
}


In this code, the lerp() function is used to calculate the current position of the object based on the percentage of time elapsed compared to the total duration. This way, the object will smoothly move from the start position to the end position over the specified duration.