From 315eaf1636621d449742f79f2cf0f37f6d2578e8 Mon Sep 17 00:00:00 2001 From: Quinn <99677023+thepigeongenerator@users.noreply.github.com> Date: Wed, 14 Aug 2024 14:37:56 +0200 Subject: [PATCH] add brick breaking --- README.md | 2 ++ src/level.c | 32 ++++++++++++++++++++++++++++++++ src/level.h | 1 + src/renderer.c | 2 +- 4 files changed, 36 insertions(+), 1 deletion(-) diff --git a/README.md b/README.md index 173bbda..140b256 100644 --- a/README.md +++ b/README.md @@ -4,3 +4,5 @@ I wanted a project to learn C and the SDL framework in, and settled upon this ga ### TODO: - make a better input system (one that doesn't crash the game) - make beeping sound effects +- make the game freeze when you lost instead of closing +- fix constants in level colision detection diff --git a/src/level.c b/src/level.c index b75768f..c35cca3 100644 --- a/src/level.c +++ b/src/level.c @@ -42,6 +42,7 @@ void level_init(Level* level) { brick->colour = colours[y]; brick->pos.x = (x * brick_width) + level_padding_left; brick->pos.y = (y * brick_height) + BRICK_PADDING_TOP; + brick->destroyed = false; } } } @@ -100,6 +101,37 @@ void level_update(Level* level, bool* keys) { ball->direction.y = -SDL_cosf(angle) * BALL_SPEED; } + // check brick collisions + for (int x = 0; x < BRICK_COLUMNS; x++) { + for (int y = 0; y < BRICK_ROWS; y++) { + const Brick* brick = &level->bricks[x][y]; + + if (brick->destroyed == true) { + continue; + } + + const float max_brick_x = brick->pos.x + BRICK_WIDTH; + const float max_brick_y = brick->pos.y + BRICK_HEIGHT; + if (ball->pos.x < max_brick_x && (ball->pos.x + ball->size) > brick->pos.x && + ball->pos.y < max_brick_y && (ball->pos.y + ball->size) > brick->pos.y) { + + // manage ball bounce direction + if (ball->direction.x > ball->direction.y) { + ball->direction.x *= -1; + } + if (ball->direction.x < ball->direction.y) { + ball->direction.y *= -1; + } + else { + ball->direction.x *= -1; + ball->direction.y *= -1; + } + + level->bricks[x][y].destroyed = true; + } + } + } + // check lose condition if ((ball->pos.y + ball->size) > SCREEN_HEIGHT) { level->stop = true; diff --git a/src/level.h b/src/level.h index fb2d461..67a7b20 100644 --- a/src/level.h +++ b/src/level.h @@ -20,6 +20,7 @@ typedef struct { typedef struct { Vector2 pos; Colour colour; + bool destroyed; } Brick; typedef struct { diff --git a/src/renderer.c b/src/renderer.c index a5b15a6..b290345 100644 --- a/src/renderer.c +++ b/src/renderer.c @@ -54,7 +54,7 @@ void renderer_update(RenderData* render_data) { for (int y = 0; y < BRICK_ROWS; y++) { Brick* brick = &level->bricks[x][y]; - if (brick == NULL) { + if (brick->destroyed == true) { continue; }