-1

I have two coordinates in a rectangular area -

   currentPosition:
      x1 = 100,
      y1 =100

   target:
         x2 = 213,
         y2 = 187

I need to calculate the shortest distance between the two coordinates using JavaScript (it can moves only in straight lines between the current position and the target).

Probably math formula is needed for the solution but I need help with it. Thanks.

Christian
  • 45
  • 5

1 Answers1

1

Use the Pythagorean theorem. Can be applied to find the distance between two points in a two-dimensional space.

calculate the shortest distance between your current position (x1, y1) and the target position (x2, y2):

function calcDistance(x1, y1, x2, y2) {
  const X = x2 - x1;
  const Y = y2 - y1;
  return Math.sqrt(X * X + Y * Y );
}