Ky -
Ky -

Reputation: 32163

How can I find the location of a point a certain distance between two others?

Let's say I have two points on a Cartesian coordinate plane, A and B, whose x and y coordinates are double-precision floats. How do I find the location of a point C that is an arbitrary percent of the distance between them?

In other words, what goes in the following method instead of "//Do magic to C"? Remember that A and B each consist of two doubles, which represent their respective x and y coordinates.

public static findProgressPoint(DoublePoint A, DoublePoint B, double position)
{
  if (position > 1 || position < 0) //Ensure that position is between 0 and 1, inclusive
    position = position - (int)position;
  DoublePoint C = new DoublePoint(0.0, 0.0);
  //Do magic to C
  return C;
}

Upvotes: 2

Views: 342

Answers (2)

Z .
Z .

Reputation: 12837

DoublePoint C = new DoublePoint( position * (A.x + B.x), position * (A.y + B.y) );

Upvotes: 1

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 727057

This should work:

double px = x1 + (x2-x1)*position;
double py = y1 + (y2-y1)*position;
DoublePoint C = new DoublePoint(px, py);

px is the x coordinate between x1 and x2 at the distance from x1 proportional to the value of position; py is the corresponding y coordinate.

Upvotes: 4

Related Questions