How can I tell if a point belongs to a certain line?
Examples are appreciated, if possible.
As an alternative to the slope/y-intercept
method, I chose this approach using Math.Atan2
:
// as an extension method
public static bool Intersects(this Vector2 v, LineSegment s) {
// check from line segment start perspective
var reference = Math.Atan2(s.Start.Y - s.End.Y, s.Start.X - s.End.X);
var aTanTest = Math.Atan2(s.Start.Y - v.Y, s.Start.X - v.X);
// check from line segment end perspective
if (reference == aTanTest) {
reference = Math.Atan2(s.End.Y - s.Start.Y, s.End.X - s.Start.X);
aTanTest = Math.Atan2(s.End.Y - v.Y, s.End.X - v.X);
}
return reference == aTanTest;
}
The first check reference
determines the arcTan from the start point of the line segment to it's end-point.
Then from the start point perspective, we determine the arcTan to the vector v
.
If those values are equal, we check from the perspective of the end-point.
Simple and handles horizontal, vertical and all else in between.