How to know if three points are clockwise or not in C / C ++?

2

Given three points p1, p2 and p3, what is the best way to know if this order is clockwise, counterclockwise, or neither (all three are collinear)?

For example, in the following image the points are clockwise:

In the same case, if the order were p1, p3, p2 they would be counterclockwise.

    
asked by anonymous 28.04.2016 / 18:58

1 answer

5

If you get the cross product of the segments on both sides of the angles, and get your signal, you will have the information of which direction the points are oriented, as shown in the code below.

// == 0: colineares; > 0: horario; < 0: anti-horario
int ordem(double ax, double ay, double bx, double by, double cx, double cy) {
    double bax = ax - bx;
    double bay = ay - by;
    double bcx = cx - bx;
    double bcy = cy - by;

    return (bax * bcy - bay * bcx);
}

int main()
{
    printf("P1, P2, P3 como em SOpt_125794: %d\n", ordem(5, 0, 0, 2, 5, 4));
    printf("P3, P2, P1 como em SOpt_125794: %d\n", ordem(5, 4, 0, 2, 5, 0));
    printf("Colineares em sequencia: %d\n", ordem(0, 0, 1, 1, 2, 2));
    printf("Colineares com terceiro ponto no meio: %d\n", ordem(0, 0, 4, 4, 2, 2));
    return 0;
}

Note that comparing exactly to zero can give you some false results because of the floating point approximation, so if you need greater accuracy, you can use something like collinear if abs (order) where epsilon is quite small.

    
28.04.2016 / 19:09