IsItSharp 369 Report post Posted April 17 Hi, i would like to know how to check as simple as possible if a point lies on a line segment (which is finite). My line has a start (x_s,y_s) and end (x_e,y_e) point and i want to check if point (x_p,y_p) is on the line, how do i do that? The only source code i found does only check if the point is on the line but not on the segment...Any help is very much appreciated. 0 Share this post Link to post Share on other sites
alvaro 21272 Report post Posted April 17 The probability of the point lying on the segment is 0, so any rounding errors would probably ruin your day. In other words, you probably don't want to be testing something like this.If you can give the segment some thickness, now it's a rectangle, and you can try to find out if the point is inside the rectangle. 3 Share this post Link to post Share on other sites
IsItSharp 369 Report post Posted April 17 Thanks for the rectangle-hint! I did it like this and i think it is working now: Line.prototype.isOnLine = function (pos) { var lowerXBound = Math.min(this.start.x, this.end.x); var upperXBound = Math.max(this.start.x, this.end.x); var lowerYBound = Math.min(this.start.y, this.end.y); var upperYBound = Math.max(this.start.y, this.end.y); return pos.x >= lowerXBound && pos.x <= upperXBound && pos.y >= lowerYBound && pos.y <= upperYBound; } Have a nice day! 0 Share this post Link to post Share on other sites
Mussi 4413 Report post Posted April 17 First get the closest point p' on the infinite line going through s and e and let d = |p' - s|. We can calculate d with vector projection: d = ((e - s) Â· (p - s)) / |(e - s)| Knowing d, we can easily get p' as follows: p' = s + d * ((e - s) / |(e - s)|) Now we can check if p lies inside the rectangle as mentioned earlier by Ãlvaro. If Îµ < d < |(e - s)| + Îµ and |p - p'| < Îµ your point lies inside the rectangle. 1 Share this post Link to post Share on other sites
abominableCodeman 0 Report post Posted July 29 (edited) You have point A(x_s,y_s) and point B(x_e,y_e) and want to check if point C(x_p,y_p) is on the line segment L<x_e - x_s, y_e - y_s>. You can check if vectors AB and AC are colinear. If their cross-product is a zero vector then they are and C is on L. That would be a fast check. If so now you have to check if it is in the bounds - you do this by using the dot product. If 0 < \(\overrightarrow{AB}\bullet\overrightarrow{AC}\) < \(\overrightarrow{AB}\bullet\overrightarrow{AB}\) then C in on L inbetween A and B Edited July 29 by abominableCodeman 0 Share this post Link to post Share on other sites
Randy Gaul 2766 Report post Posted July 31 Here's all the math for a problem like this: http://www.randygaul.net/2014/07/23/distance-point-to-line-segment/ After getting a squared distance make sure the distance value is below some threshold, and consider below the threshold as "on the line segment". 1 Share this post Link to post Share on other sites