Fez Vrasta
Fez Vrasta

Reputation: 14835

Find angle between 3 points in 3D space with JavaScript

I have 3 points that define an angle in a 3D space.

const start = [-73.52361290322581, -20, -41.69909677419352];
const middle = [-100.63483870967742, -20, -71.23096774193547];
const end = [-60.93625806451613, -20, -80.91354838709677];

I need to find the angle between the 3 points, so the angle between the vector start-middle, and the middle-end.

So far I only found Python solutions that use specific linear algebra libraries to do the calculations, but I'm looking for something in plain JavaScript.

I managed to put together a function to calculate the angle on a 2D space, but I need it on a 3D one.

function radiansToDegrees(radians) {
  var pi = Math.PI;
  return radians * (180 / pi);
}
function getAngle(a, b, c) {
  const ang = radiansToDegrees(
    Math.atan2(c[1] - b[1], c[0] - b[0]) - Math.atan2(a[1] - b[1], a[0] - b[0])
  );
  return ang < 0 ? ang + 360 : ang;
}

Upvotes: 1

Views: 847

Answers (1)

Heisen
Heisen

Reputation: 148

Why don't you use the law of cosines?

const a = [-73.52361290322581, -20, -41.69909677419352];
const b = [-100.63483870967742, -20, -71.23096774193547];
const c = [-60.93625806451613, -20, -80.91354838709677];

// Function to convert radians to degrees
function radians_to_degrees(radians) {
    return radians * (180 / Math.PI);
}

// Function to find the distance between 2 points in a 3D plane
function dist(p1, p2) {
    return Math.sqrt(
        Math.pow(p1[0] - p2[0], 2) +
        Math.pow(p1[1] - p2[1], 2) +
        Math.pow(p1[2] - p2[2], 2)
    ); 
}

// Function to find the angle in 3D space
function find_angle(a, b, c) {
    const ab = dist(a, b);
    const bc = dist(b, c);
    const ac = dist(a, c);

    const angle = (Math.pow(ab, 2) + Math.pow(bc, 2) - Math.pow(ac, 2)) / 
(2 * ab * bc);
    return radians_to_degrees(Math.acos(angle));
}  

console.log(find_angle(a, b, c));

Upvotes: 5

Related Questions