diff --git a/src/game.cpp b/src/game.cpp index 958ca7e..8be1f75 100644 --- a/src/game.cpp +++ b/src/game.cpp @@ -16,6 +16,37 @@ const float BALL_RADIUS = 12.5f; BallObject* ball; +// AABB with AABB collision detection +bool CheckCollisions(GameObject& one, GameObject& two) +{ + // Collision on the X-Axis + bool CollisionX = one.Position.x + one.Size.x >= two.Position.x && + two.Position.x + two.Size.x >= one.Position.x; + // Colision on the y-Axis + bool CollisionY = one.Position.y + one.Size.y >= two.Position.y && + two.Position.y + two.Size.y >= one.Position.y; + + return CollisionX && CollisionY; +} + +// AABB with circle collision detection +bool CheckCollisions(BallObject& one, GameObject& two) +{ + // Calculate the closest point on two's border to the center point of one + glm::vec2 center (one.Position + one.Radius); + glm::vec2 aabb_half_extents(two.Size.x /2.0f, two.Size.y / 2.0f); + glm::vec2 aabb_center(two.Position.x + aabb_half_extents.x, two.Position.y + aabb_half_extents.y ); + + glm::vec2 difference = center - aabb_center; + glm::vec2 clamped = glm::clamp(difference, -aabb_half_extents, aabb_half_extents); + + glm::vec2 closest = aabb_center + clamped; + + // Calculate the distance and check if it is less then two's radius + difference = closest - center; + return glm::length(difference) < one.Radius; +} + Game::~Game() @@ -69,6 +100,24 @@ void Game::Init() } +void Game::DoCollisions() +{ + for(GameObject& box: this->Levels[this->Level].Bricks) + { + if(!box.Destroyed) + { + if(CheckCollisions(*ball, box)) + { + if(!box.IsSolid) + { + box.Destroyed = true; + } + } + } + } +} + + void Game::ProcessInput(float dt) { if(this->State == GAME_ACTIVE) @@ -107,6 +156,7 @@ void Game::ProcessInput(float dt) void Game::Update(float dt) { ball->Move(dt, this->Width); + this->DoCollisions(); } void Game::Render() diff --git a/src/game.h b/src/game.h index e3eb190..d19b7c6 100644 --- a/src/game.h +++ b/src/game.h @@ -35,6 +35,7 @@ class Game { void ProcessInput(float dt); void Update(float dt); void Render(); + void DoCollisions(); };