From 4abb5e4664654591ba8beecf7774b69365c46d14 Mon Sep 17 00:00:00 2001 From: Victor Gamper Date: Sun, 26 Jan 2020 19:45:20 +0100 Subject: Added a collision detection --- PidginImage.c | 15 ++++++++++----- catch.c | 26 +++++++++++++++++++++++--- catch.h | 4 +++- 3 files changed, 36 insertions(+), 9 deletions(-) diff --git a/PidginImage.c b/PidginImage.c index 70dcb78..969fad0 100644 --- a/PidginImage.c +++ b/PidginImage.c @@ -7,7 +7,7 @@ #include "pidgin_image.h" #include "catch.h" -static int animation_index = 0, ax = 1; +static int animation_index = 0, delay, ax = 1; static SDL_Rect sdl_rect_output, sdl_rect_source; static SDL_Surface* image_pidgin; @@ -29,8 +29,13 @@ void draw_Pidgin(SDL_Surface* surface, int x, int y) { } void Pidgin_IncrementFrame() { - animation_index+=ax; - sdl_rect_source.y = animation_index * PIDGIN_HEIGHT; - if(animation_index > 1) ax = -1; - if(animation_index < 1) ax = 1; + delay++; + //printf("%d\n", delay); + if(delay >= 50) { + delay = 0; + animation_index+=ax; + sdl_rect_source.y = animation_index * PIDGIN_HEIGHT; + if(animation_index > 1) ax = -1; + if(animation_index < 1) ax = 1; + } } diff --git a/catch.c b/catch.c index e2168ff..4c560a4 100644 --- a/catch.c +++ b/catch.c @@ -235,12 +235,22 @@ void gameRoutine() { if(state == STATE_GAME) { for(int i = 0; i screen->w) + // if the bird left the screen, reset it + if(bird[i].x > screen->w) { bird[i].type = BIRD_TYPE_NONE; + } + else { + + // check if the bird collided with the cat + if(checkCollision(cat.x, cat.y, image_cat->w, image_cat->h, bird[i].x, bird[i].y, image_cat->w, image_cat->h)) { + bird[i].type = BIRD_TYPE_NONE; + } + } } else { // there should be a 1 in 10 chance for a bird to spawn if(getRandomInt(10) == 1) { @@ -253,6 +263,16 @@ void gameRoutine() { } } +bool checkCollision(int x1, int y1, int w1, int h1, int x2, int y2, int w2, int h2) { + if(y1 > y2 + h2) return false; + if(y2 > y1 + h1) return false; + if(x1 > x2 + w2) return false; + if(x2 > x1 + w1) return false; + + return true; +} + + int getRandomInt(int limit) { return rand() % (limit+1); } diff --git a/catch.h b/catch.h index 9ae7b9b..0019917 100644 --- a/catch.h +++ b/catch.h @@ -40,12 +40,14 @@ struct Cat { }; struct Bird { - int x, y; + float x; + int y; unsigned char type; }; // function predefines extern void gameRoutine(); +extern bool checkCollision(int x1, int y1, int w1, int h1, int x2, int y2, int w2, int h2); // BitmapFontRenderer.c extern void Font_Init(); -- cgit v1.2.3