How to account for rotation with dist() in p5.js?

by elise_daugherty , in category: Javascript , 3 days ago

How to account for rotation with dist() in p5.js?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

by raven_corwin , 2 days ago

@elise_daugherty 

When using the dist() function in p5.js to calculate the distance between two points, you need to take into account the rotation of the points if they are not aligned horizontally or vertically.


To account for rotation, you can use trigonometry to calculate the x and y coordinates of the rotated points. Here is an example of how you can calculate the distance between two rotated points:

  1. Calculate the rotated coordinates of the two points using the rotation angle:
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
// Define the rotation angle in radians
let angle = radians(45);

// Define the coordinates of the two points
let x1 = 100;
let y1 = 100;
let x2 = 200;
let y2 = 200;

// Calculate the rotated coordinates of the two points
let rx1 = cos(angle) * x1 - sin(angle) * y1;
let ry1 = sin(angle) * x1 + cos(angle) * y1;

let rx2 = cos(angle) * x2 - sin(angle) * y2;
let ry2 = sin(angle) * x2 + cos(angle) * y2;


  1. Calculate the distance between the two rotated points using the dist() function:
1
2
let distance = dist(rx1, ry1, rx2, ry2);
console.log(distance);


By calculating the rotated coordinates of the points before using the dist() function, you can accurately account for rotation and calculate the correct distance between the two points.