U
U
Urukhayy2015-02-03 12:17:25
Programming
Urukhayy, 2015-02-03 12:17:25

How to find the length of the perpendicular from a point to a line segment?

There is a point A(x,y).
There is a segment with the beginning B(x1,y1) and the end C(x2,y2).
It is required to find a perpendicular dropped from a point to a segment.
I tried using the triangle height formula - www.fxyz.ru/%D1%84%D0%BE%D1%80%D0%BC%D1%83%D0%BB%D...
But the thing is, if the point does not lie above the segment (that is, there is emptiness under the point), then the result will be as if the segment is still under the point. In other words, as if the segment is infinite.

Answer the question

In order to leave comments, you need to log in

2 answer(s)
M
Mrrl, 2015-02-03
@Urukhayy

double L=(x1-x2)*(x1-x2)+(y1-y2)*(y1-y2);
double PR=(x-x1)*(x2-x1)+(y-y1)*(y2-y1);
bool res=true;
double cf=PR/L;
if(cf<0){ cf=0; res=false; }
if(cf>1){ cf=1; res=false; }
double xres=x1+cf*(x2-x1);
double yres=y1+cf*(y2-y1);
In (xres, yres) there will be coordinates of the nearest point of the segment, and the variable res will show whether the perpendicular turned out or not.

J
jcmvbkbc, 2015-02-03
@jcmvbkbc

A straight line perpendicular to a line passing through a given point can be constructed in a unique way. If your segment does not contain a point of intersection with a perpendicular, then it is impossible to construct a perpendicular "to the segment".

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question