Check is a point (x,y) is between two points drawn on a straight line

后端 未结 7 955
青春惊慌失措
青春惊慌失措 2020-11-27 06:18

I have drawn a line between two points A(x,y)---B(x,y) Now I have a third point C(x,y). I want to know that if C lies on the line which is drawn between A and B. I want to

7条回答
  •  粉色の甜心
    2020-11-27 06:55

    if (distance(A, C) + distance(B, C) == distance(A, B))
        return true; // C is on the line.
    return false;    // C is not on the line.
    

    or just:

    return distance(A, C) + distance(B, C) == distance(A, B);
    

    The way this works is rather simple. If C lies on the AB line, you'll get the following scenario:

    A-C------B
    

    and, regardless of where it lies on that line, dist(AC) + dist(CB) == dist(AB). For any other case, you have a triangle of some description and 'dist(AC) + dist(CB) > dist(AB)':

    A-----B
     \   /
      \ /
       C
    

    In fact, this even works if C lies on the extrapolated line:

    C---A-------B
    

    provided that the distances are kept unsigned. The distance dist(AB) can be calculated as:

      ___________________________
     /           2              2
    V (A.x - B.x)  + (A.y - B.y)
    

    Keep in mind the inherent limitations (limited precision) of floating point operations. It's possible that you may need to opt for a "close enough" test (say, less than one part per million error) to ensure correct functioning of the equality.

提交回复
热议问题