This is basic graphics geometry and/or trig, and I feel dumb for asking it, but I can't remember how this goes. So:
- I have a line defined by two points (x1, y1) and (x2, y2).
- I have a third point (xp, yp) which lies somewhere else.
I want to compute the point (x', y') that lies somewhere along the line in #1, such that, when joined with the point from #2, creates a new perpendicular line to the first line.
Thanks.
The answer line is:
How the result was obtained:
Just calculate the answer from the lines after this (this is too long... I am hungry).
You can find that point by considering first a generic point
(x, y)
along the line from(x1, y1)
to(x2, y2)
:and the computing the (squared) distance from this point from
(xp, yp)
that substituting the definition of
x
andy
givesthen to find the minimum of this distance varying
t
we deriveE
with respect tot
that after some computation gives
looking for when this derivative is zero we get an explicit equation for
t
so the final point can be computed using that value for
t
in the definition of(x, y)
.Using vector notation this is exactly the same formula suggested by Gareth...
where the notation
<a, b>
represents the dot product operationax*bx + ay*by
.Note also that the very same formula works in an n-dimensional space.
You can solve the slope of the line connecting
(x1, y1)
and(x2, y2)
. You then know the perpendicular line has a slope negative-inverse of that.To find the y-intercept, use the slope to see how far the line travels in
y
fromx=0
tox1
.You can then get the formulas for the line between your two points and the line from
(xp, yp)
with the above slope. For a given x, they have equal y's, so you can solve for thatx
, then plug that into either's formula for they
.Thus the equations for the lines are of the form
y = mx + b
Points 1 and 2:
y(x) = mx + b
Point p:
y(x) = nx + c
Set their
y
's equal to find x'And thus use either formula to compute y'
y' = mx' + b
To all those poor souls looking for a concrete example using vectors... here I build upon Gareth's answer.
You have a vector from p to r (from 0,0 to 50,-50) and another point, q, which is at (50, 0). The right-angle intersection of q and the vector from p to r is { x: 25. y: -25 } and is derived with the following code.
A useful rule of thumb in this kind of computational geometry is that you should work with vectors as long as you can, switching to Cartesian coordinates only as a last resort. So let's solve this using vector algebra. Suppose your line goes from p to p + r, and the other point is q.
Now, any point on the line, including the point you are trying to find (call it s), can be expressed as s = p + λ r for a scalar parameter λ.
Now the vector from q to s must be perpendicular to r. Therefore
Where · is the dot product operator. Expand the product:
And divide:
When you come to implement it, you need to check whether r · r = 0, to avoid division by zero.