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.
When given the end points of a line segment, you can find out its midpoint by using the midpoint formula. As the name might have already suggested, midpoint is basically the halfway between two end points. All you need to do is dividing the sum of x-values and the sum of y-values by 2.
The cross product of A B → and A C → equal to 0 means that the vectors are colinear or that the points and or and coincide. If the cross product is not equal to zero, the point doesn't belongs on the segment.
A line segment is the set of all points on a line bounded by two other points, called endpoints. For example, the line segment between endpoints $$ A and $$ B is denoted $$ A B or segment $$ A B .
Check if the cross product of (b-a) and (c-a) is 0, as tells Darius Bacon, tells you if the points a, b and c are aligned.
But, as you want to know if c is between a and b, you also have to check that the dot product of (b-a) and (c-a) is positive and is less than the square of the distance between a and b.
In non-optimized pseudocode:
def isBetween(a, b, c): crossproduct = (c.y - a.y) * (b.x - a.x) - (c.x - a.x) * (b.y - a.y) # compare versus epsilon for floating point values, or != 0 if using integers if abs(crossproduct) > epsilon: return False dotproduct = (c.x - a.x) * (b.x - a.x) + (c.y - a.y)*(b.y - a.y) if dotproduct < 0: return False squaredlengthba = (b.x - a.x)*(b.x - a.x) + (b.y - a.y)*(b.y - a.y) if dotproduct > squaredlengthba: return False return True
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With