diff options
author | P. J. McDermott <pj@pehjota.net> | 2021-03-30 03:15:17 (EDT) |
---|---|---|
committer | P. J. McDermott <pj@pehjota.net> | 2021-03-30 03:15:17 (EDT) |
commit | 8062ca04f1c007359badf63352c320067a608252 (patch) | |
tree | 108d5864c1b2b3893a0428c841b92d0090d631e9 | |
parent | 238a78197b13c0784c922cd665af8c3912600a86 (diff) | |
download | dodge-balls-8062ca04f1c007359badf63352c320067a608252.zip dodge-balls-8062ca04f1c007359badf63352c320067a608252.tar.gz dodge-balls-8062ca04f1c007359badf63352c320067a608252.tar.bz2 |
collision: Add basic circle-line test
-rw-r--r-- | src/collision.c | 50 | ||||
-rw-r--r-- | src/collision.h | 3 |
2 files changed, 53 insertions, 0 deletions
diff --git a/src/collision.c b/src/collision.c index 7e77b0a..758f28c 100644 --- a/src/collision.c +++ b/src/collision.c @@ -38,6 +38,56 @@ db_pt_in_rect(int x, int y, SDL_Rect *rect) return 1; } +int +db_col_cir_line(double cir_x, double cir_y, double cir_r, + int line_x1, int line_y1, int line_x2, int line_y2, + double *col_x, double *col_y) +{ + int line_min; + int line_max; + + if (line_y1 == line_y2) { + /* Horizontal line */ + if (line_x1 < line_x2) { + line_min = line_x1; + line_max = line_x2; + } else { + line_min = line_x2; + line_max = line_x1; + } + if (cir_x < line_min) { + *col_x = line_min; + } else if (cir_x > line_max) { + *col_x = line_max; + } else { + *col_x = cir_x; + } + *col_y = line_y1; + } else if (line_x1 == line_x2) { + /* Vertical line */ + if (line_y1 < line_y2) { + line_min = line_y1; + line_max = line_y2; + } else { + line_min = line_y2; + line_max = line_y1; + } + if (cir_y < line_min) { + *col_y = line_min; + } else if (cir_y > line_max) { + *col_y = line_max; + } else { + *col_y = cir_y; + } + *col_x = line_x1; + } else { + return -1; + } + return (cir_r * cir_r) >= + ((*col_x - cir_x) * (*col_x - cir_x) + + (*col_y - cir_y) * (*col_y - cir_y)); +} + void db_closest_pt_on_rect(int x, int y, SDL_Rect *rect, double *close_x, double *close_y) diff --git a/src/collision.h b/src/collision.h index ee04a8e..de1b2ca 100644 --- a/src/collision.h +++ b/src/collision.h @@ -23,6 +23,9 @@ #include <SDL.h> int db_pt_in_rect(int x, int y, SDL_Rect *rect) __attribute__((__pure__)); +int db_col_cir_line(double cir_x, double cir_y, double cir_r, + int line_x1, int line_y1, int line_x2, int line_y2, + double *col_x, double *col_y); void db_closest_pt_on_rect(int x, int y, SDL_Rect *rect, double *close_x, double *close_y); int db_col_cir_rect(int x, int y, int r, SDL_Rect *rect, |