Find if point lays on line segment

前端 未结 12 1199
抹茶落季
抹茶落季 2020-11-30 04:01

I have line segment defined by two points A(x1,y1,z1) and B(x2,y2,z2) and point p(x,y,z). How can I check if the point lays on the line segment?

相关标签:
12条回答
  • 2020-11-30 04:48

    Find the distance of point P from both the line end points A, B. If AB = AP + PB, then P lies on the line segment AB.

    AB = sqrt((x2-x1)*(x2-x1)+(y2-y1)*(y2-y1)+(z2-z1)*(z2-z1));
    AP = sqrt((x-x1)*(x-x1)+(y-y1)*(y-y1)+(z-z1)*(z-z1));
    PB = sqrt((x2-x)*(x2-x)+(y2-y)*(y2-y)+(z2-z)*(z2-z));
    if(AB == AP + PB)
        return true;
    
    0 讨论(0)
  • 2020-11-30 04:51

    The cross product (B - A) × (p - A) should be much much shorter than B - A. Ideally, the cross product is zero, but that's unlikely on finite-precision floating-point hardware.

    0 讨论(0)
  • 2020-11-30 04:51

    You could check if the point lies between the two planes defined by point1 and point2 and the line direction:

    ///  Returns the closest point from @a point to this line on this line.
    vector3 <Type>
    line3d <Type>::closest_point (const vector3 <Type> & point) const
    {
        return this -> point () + direction () * dot (point - this -> point (), direction ());
    }
    
    ///  Returns true if @a point lies between point1 and point2.
    template <class Type>
    bool
    line_segment3 <Type>::is_between (const vector3 <Type> & point) const
    {
        const auto closest = line () .closest_point (point);
        return abs ((closest - point0 ()) + (closest - point1 ())) <= abs (point0 () - point1 ());
    }
    
    0 讨论(0)
  • 2020-11-30 04:52

    First take the cross product of AB and AP. If they are colinear, then it will be 0.

    At this point, it could still be on the greater line extending past B or before A, so then I think you should be able to just check if pz is between az and bz.

    This appears to be a duplicate, actually, and as one of the answers mentions, it is in Beautiful Code.

    0 讨论(0)
  • 2020-11-30 04:53

    If the point is on the line then:

    (x - x1) / (x2 - x1) = (y - y1) / (y2 - y1) = (z - z1) / (z2 - z1)
    

    Calculate all three values, and if they are the same (to some degree of tolerance), your point is on the line.

    To test if the point is in the segment, not just on the line, you can check that

    x1 < x < x2, assuming x1 < x2, or
    y1 < y < y2, assuming y1 < y2, or
    z1 < z < z2, assuming z1 < z2
    
    0 讨论(0)
  • 2020-11-30 04:53

    Let V1 be the vector (B-A), and V2 = (p-A), normalize both V1 and V2.

    If V1==(-V2) then the point p is on the line, but preceding A, & therefore not in the segment. If V1==V2 the point p is on the line. Get the length of (p-A) and check if this is less-or-equal to length of (B-A), if so the point is on the segment, else it is past B.

    0 讨论(0)
提交回复
热议问题