I need find the line perpendicular to another line (defined by two points it passes through) and intersects a specific point (defined by its coordinates). I need to calculate the length of the segement of the line I need to find between the line it is perpendicular to and the point. It is similar to how finding the height of a triangle works. In the example below the line would be defined by the points: A(0, 0), B(4, 1) and the point it should intersect would be C(-1, 2).
I know this can easily be calculated with the pythagoras theorem but it just throws me off when the line isn't vertical/horizontal.
Make vectors
AB = (abx, aby) = (B.x - A.x, B.y - A.y)
AC = (acx, acy) = (C.x - A.x, C.y - A.y)
The simplest form of projection of C
onto A—B
line, using the dot product, is:
AD = AB * (AB dot AC) / (AB dot AB)
D = (dx, dy) = A + AD
In coordinates:
coeff = (abx*acx + aby*acy) / (abx*abx+aby*aby)
dx = A.x + abx * coeff
dy = A.y + aby * coeff
D
point is projection of C
onto A—B
line. If you need CD
length, get
CDlen = sqrt((cx-dx)^2+(cy-dy)^2)
(or use Math.Hypot
function in some languages)