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

Asked

Viewed 364 times

2

Given three points P1, P2 and P3, what is the best way to know whether this order is clockwise, counterclockwise, or neither (the three are collinear)?

For example, in the image below the dots are clockwise:

Pontos no sentido horário.

In this same case, if the order were P1, P3, P2 they would be counterclockwise.

  • And what have you done? Put a [mcve] and your specific question.

1 answer

5


If you get the cross product of the segments on both sides of the angles, and pick up your signal, you will have 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 with zero can give you some false results because of the floating point approximation, so if you need greater precision, you can use something like (colineares se abs(order) < Epsilon), where Epsilon is a very small value.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.