Answer the question
In order to leave comments, you need to log in
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
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.
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question