1

Using Python 2.7.3 and Pygame 1.9.1.

I have a line and I only know the co-ordinates of endpoints A and B.
I want to calculate what are the co-ordinates AB, given a value on x or y axis.
For Example
Image Example

Here I know
(x,y) of A , B&C
Also,
C is on X-axis or Y axis.
My Question
How do I calculate the position of the Co-ordinates(x,y) of point D

pradyunsg
  • 18,287
  • 11
  • 43
  • 96

1 Answers1

2

The equation of the straight line is:

y = mx + q

What you want is either y(x) or x(y), and you have the two endpoints (x1, y1) and (x2, y2). Replace them in the straight-line equation and set up a linear system:

y1 = m·x1 + q
y2 = m·x2 + q

Subtraction yields:

y2-y1 = m(x2-x1) => m = (y2-y1)/(x2-x1)

and q is obviously:

q = y2-m·x2

so, now you have your y = f(x) representing the straight line connecting your two points.

Obviously, a vertical line cannot be represented in this form (m->+inf), and, if you are trying to trace a line on pixels evaluating this function for every x, you'll get vertical "holes".
In both these cases, you should use the x = f(y) form (that you can obtain following these same steps, but starting from the equation x = py + r).

That being said, you can get the y of D knowing its x by just putting such x in the equation of the straight line (y = f(x)) determined above; the same holds (with the inverse relation, x = f(y)) if you know the y and want to determine the x.

Daniel Hilgarth
  • 171,043
  • 40
  • 335
  • 443
Matteo Italia
  • 123,740
  • 17
  • 206
  • 299