Let's say you have a two dimensional plane with 2 points (called a and b) on it represented by an x integer and a y integer for each point.
How can you determine if another point c is on the line segment defined by a and b?
I use python most, but examples in any language would be helpful.
Here's how I did it at school. I forgot why it is not a good idea.
EDIT:
@Darius Bacon: cites a "Beautiful Code" book which contains an explanation why the belowed code is not a good idea.
Any point on the line segment (a, b) (where a and b are vectors) can be expressed as a linear combination of the two vectors a and b:
In other words, if c lies on the line segment (a, b):
Solving for m, we get:
So, our test becomes (in Python):
Here is some Java code that worked for me:
Check if the cross product of
b-a
andc-a
is0
: that means all the points are collinear. If they are, check ifc
's coordinates are betweena
's andb
's. Use either the x or the y coordinates, as long asa
andb
are separate on that axis (or they're the same on both).This answer used to be a mess of three updates. The worthwhile info from them: Brian Hayes's chapter in Beautiful Code covers the design space for a collinearity-test function -- useful background. Vincent's answer helped to improve this one. And it was Hayes who suggested testing only one of the x or the y coordinates; originally the code had
and
in place ofif a.x != b.x else
.how about just ensuring that the slope is the same and the point is between the others?
given points (x1, y1) and (x2, y2) ( with x2 > x1) and candidate point (a,b)
if (b-y1) / (a-x1) = (y2-y2) / (x2-x1) And x1 < a < x2
Then (a,b) must be on line between (x1,y1) and (x2, y2)
Here is my solution with C# in Unity.