LoginSignup
1
1

線分の交差判定

Posted at

検索で引っかかったものがコーナーケースに引っかかるようだったので

int cross_product(point_t a, point_t b, point_t c) {
    return (b.x - a.x) * (c.y - a.y) - (b.y - a.y) * (c.x - a.x);
}

int is_intersect(point_t a, point_t b, point_t c, point_t d) {
    int cp1 = cross_product(a, b, c);
    int cp2 = cross_product(a, b, d);
    int cp3 = cross_product(c, d, a);
    int cp4 = cross_product(c, d, b);

    if (((cp1 > 0 && cp2 < 0) || (cp1 < 0 && cp2 > 0)) && ((cp3 > 0 && cp4 < 0) || (cp3 < 0 && cp4 > 0))) {
        return 1;
    }
    if (cp1 == 0 && cp2 == 0 && cp3 == 0 && cp4 == 0) {
        if ((a.x <= c.x && c.x <= b.x) || (a.x <= d.x && d.x <= b.x) || (c.x <= a.x && a.x <= d.x) || (c.x <= b.x && b.x <= d.x)) {
            return 1;
        }
    }
    return 0;
}
1
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
1