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

后端 未结 7 966
青春惊慌失措
青春惊慌失措 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:45

    ATTENTION! Math-only!

    Try this!

    You can try this formula. Put your A(x1, y1) and B(x2, y2) coordinates to formula, then you'll get something like

    y = k*x + b; // k and b - numbers
    

    Then, any point which will satisfy this equation, will lie on your line. To check that C(x, y) is between A(x1, y1) and B(x2, y2), check this: (x1x>x2 && y1>y>y2).

    Example

    A(2,3) B(6,5)
    

    The equation of line:

    (y - 3)/(5 - 3) = (x - 2)/(6 - 2)
    (y - 3)/2 = (x - 2)/4
    4*(y - 3) = 2*(x - 2)
    4y - 12 = 2x - 4
    4y = 2x + 8
    y = 1/2 * x + 2; // equation of line. k = 1/2, b = 2;
    

    Let's check if C(4,4) lies on this line.

    2<4<6 & 3<4<5 // C between A and B
    

    Now put C coordinates to equation:

    4 = 1/2 * 4 + 2
    4 = 2 + 2 // equal, C is on line AB
    

    PS: as @paxdiablo wrote, you need to check if line is horizontal or vertical before calculating. Just check

    y1 == y2 || x1 == x2
    

提交回复
热议问题