Reputation: 13078
Suppose you have the following three points A
, B
, and C
as shown in the following picture:
The points are always sorted according to their vertical offset, so the top most point is always A. Sometimes B and C could have the same y coordinate.
I'm trying to find the x coordinate for point D. I can find the Y coordinate for D by interpolating points A.y
and C.y
at (B.y / (C.y - A.y))
. I'm doing my interpolation using the following formula (in C++)
float linearInterpolation(float a, float b, float t)
{
return a + (t * (b - a));
}
So in other words, D.y = linearInterpolation(A.y, C.y, (B.y - A.y) / (C.y - A.y))
So to summarize, my question is: how do I find D.x
?
Thanks
--
Answer:
Just to clarify, here's the solution that was suggested and worked:
D.x = A.x + (B.y - A.y) * (C.x - A.x) / (C.y - A.y);
D.y = B.y;
As illustrated in the image below:
Upvotes: 4
Views: 3251
Reputation: 14031
It it is the x coordinate that requires interpolation. The y coordinates of B and D are equal on your diagram.
D.x = A.x + (B.y - A.y) * (C.x - A.x) / (C.y - A.y);
D.y = B.y;
You should also make a provision for the case of C.y == A.y, where D.x could be anywhere between A.x and C.x. One way to do this is to not draw triangles, for which abs(C.y - A.y) < delta
, with the delta
being on the order of magnitude of 1 pixel.
Upvotes: 7
Reputation: 490108
D.y = B.y
delta_x = C.x - A.x
delta_y = C.y - A.y
dist_y = B.y - A.y
percent = dist_y / delta_y
D.x = A.x + percent * delta_x
Upvotes: 2
Reputation:
The function for the line AC is y = mx + b
.
m = (A.y - C.y)/(A.x - C.x)
You can then substitute A in: A.y = A.x * m + b
b = A.y - A.x *m
You need to calculate x from y, so swap the function around.
mx = y -b
x = (y -b)/m
Those are three steps to find the x from the y along that side of a triangle. Note that you don't need to do any interpolation to find Dy. Simply, D.y = B.y.
Note that you can probably optimize what I have just written into a smaller series of steps. I think its better to write easier to read code though.
Upvotes: 1