diff options
| author | fschildt <florian.schildt@protonmail.com> | 2026-01-20 22:05:26 +0100 |
|---|---|---|
| committer | fschildt <florian.schildt@protonmail.com> | 2026-01-20 22:05:26 +0100 |
| commit | e62fd87d463e877e93701801095f9882956d165d (patch) | |
| tree | 286b4646b5772b5756511c93a75f0e6dadf19fbd /src/games/breakout | |
| parent | 028fdb5b30befb1200f9f6ea8e8e247dc7bed50a (diff) | |
breakout: add collision between paddle and ball
Diffstat (limited to 'src/games/breakout')
| -rw-r--r-- | src/games/breakout/Breakout.cpp | 25 | ||||
| -rw-r--r-- | src/games/breakout/Breakout.hpp | 4 |
2 files changed, 25 insertions, 4 deletions
diff --git a/src/games/breakout/Breakout.cpp b/src/games/breakout/Breakout.cpp index 62ee17c..38d356c 100644 --- a/src/games/breakout/Breakout.cpp +++ b/src/games/breakout/Breakout.cpp @@ -3,6 +3,7 @@ #include "games/Game.hpp" #include "common/shapes.hpp" #include "renderer/Renderer.hpp" +#include <cmath> void @@ -17,7 +18,7 @@ Breakout::Start() m_ball.circle.y = 2.0f; m_ball.circle.r = 0.05f; m_ball.dx = 0.0f; - m_ball.dy = 1.0f; + m_ball.dy = BALL_SPEED; float brickmap_w = 1.00f * MAP_WIDTH; @@ -126,14 +127,32 @@ Breakout::MoveBall(float dt) } // collision paddle + // Todo: Handle collisions on the side of the paddle near the bottom. + // Those should end up in game over somehow. Rectangle paddle_rect = { m_paddle.x, 0.0f, m_paddle.x + PADDLE_WIDTH, PADDLE_HEIGHT }; - if (Intersect_Rectangle_Circle(paddle_rect, m_ball.circle)) { - m_ball.dy = std::abs(m_ball.dy); + if (Intersect_AABB_Circle(paddle_rect, m_ball.circle)) { + // Todo: find a better name than 'percent' (which represents [0.0, 1.0] here instead of the expected [0, 100]). + float rect_half_width = (paddle_rect.x1 - paddle_rect.x0) / 2; + float rect_center_x = paddle_rect.x0 + rect_half_width; + float dist_x = m_ball.circle.x - rect_center_x; + float dist_x_percent = dist_x / rect_half_width; + + float max_dx_percent = 0.7f; + float dx_percent = dist_x_percent * max_dx_percent; + float dy_percent = 1.0f - dx_percent; + + float length = std::sqrt(dx_percent*dx_percent + dy_percent*dy_percent); + float dx = BALL_SPEED * (dx_percent / length); + float dy = BALL_SPEED * (dy_percent / length); + + m_ball.circle.y += paddle_rect.y1 -(m_ball.circle.y - m_ball.circle.r); + m_ball.dx = dx; + m_ball.dy = dy; } } diff --git a/src/games/breakout/Breakout.hpp b/src/games/breakout/Breakout.hpp index 2b7c9b3..60cd648 100644 --- a/src/games/breakout/Breakout.hpp +++ b/src/games/breakout/Breakout.hpp @@ -22,8 +22,10 @@ class Breakout : public Game { static constexpr uint32_t BRICK_ROWS = 8; static constexpr uint32_t BRICK_COLS = 14; - static constexpr float PADDLE_HEIGHT = 0.1f; + static constexpr float BALL_SPEED = 2.0f; + static constexpr float PADDLE_WIDTH = 0.6f; + static constexpr float PADDLE_HEIGHT = 0.1f; static constexpr float PADDLE_SPEED = 1.0f; |
