Manuel
Manuel

Reputation: 10303

how to find a point in the path of a line

I've got two points between which im drawing a line (x1,y1 and x2,y2) but i need to know the coordinates of x3,y3 which is gapSize away from point x2,y2. Any ideas on how to solve this problem (the program is written in objective-c if that is helpful at all)?

example

Upvotes: 0

Views: 656

Answers (3)

user85109
user85109

Reputation:

There are many ways to do this. Simplest (to me) is the following. I'll write it in terms of mathematics since I can't even spell C.

Thus, we wish to find the point C = {x3,y3}, given points A = {x1,y1} and B = {x2,y2}.

The distance between the points is

d = ||B-A|| = sqrt((x2-x1)^2 + (y2-y1)^2)

A unit vector that points along the line is given by

V = (B - A)/d = {(x2 - x1)/d, (y2-y1)/d}

A new point that lies a distance of gapSize away from B, in the direction of that unit vector is

C = B + V*gapSize = {x2 + gapSize*(x2 - x1)/d, y2 + gapSize*(y2 - y1)/d}

Upvotes: 1

Tregoreg
Tregoreg

Reputation: 22196

You can simply calculate the angle in radians as

double rads = atan2(y2 - y1, x2 - x1);

Then you get the coordinates as follows:

double x3 = x2 + gapSize * cos(rads);
double y3 = y2 + gapSize * sin(rads);

Is this what you meant?

Upvotes: 6

mprivat
mprivat

Reputation: 21902

Compute the distance between P1 and P2: d=sqrt( (y2-y1)^2 + (x2-x1)^2)

Then x2 = (d*x1 + gapSize*x3) / (d+gapSize)

So x3 = (x2 * (d+gapSize) - d*x1) / gapSize

Similarly, y3 = (y2 * (d+gapSize) - d*y1) / gapSize

Sorry for the math. I didn't try to code it but it sounds right. I hope this helps.

Upvotes: 1

Related Questions