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

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

    I believe the simplest is

    // is BC inline with AC or visa-versa
    public static boolean inLine(Point A, Point B, Point C) {
       // if AC is vertical
       if (A.x == C.x) return B.x == C.x;
       // if AC is horizontal
       if (A.y == C.y) return B.y == C.y;
       // match the gradients
       return (A.x - C.x)*(A.y - C.y) == (C.x - B.x)*(C.y - B.y);
    }
    

    You can calculate the gradient by taking the difference in the x values divided by the difference in the y values.

    Note: there is a different test to see if C appears on the line between A and B if you draw it on a screen. Maths assumes that A, B, C are infinitely small points. Actually very small to within representation error.

提交回复
热议问题