diff --git a/src/ball.cpp b/src/ball.cpp index 6992f11..39d69c3 100644 --- a/src/ball.cpp +++ b/src/ball.cpp @@ -12,7 +12,7 @@ double getRandomDouble(double maxValue); -Ball::Ball(QWidget* parent) : m_parent{parent}, m_isSpawning{true} { +Ball::Ball(QWidget* parent, std::shared_ptr platform) : m_parent{parent}, m_platform{platform}, m_isSpawning{true} { QRect rct = parent->rect(); m_x = rand() % rct.width(); // random x pos @@ -49,6 +49,11 @@ void Ball::timerEvent(QTimerEvent*) { return; } + // Platform collision (only if no longer spawning) + if (!m_isSpawning && m_platform->rect().intersects(QRect(m_x, m_y, RADIUS * 2.0, RADIUS * 2.0))) { + m_ky *= -1; + } + m_x += m_kx; m_y += m_ky; diff --git a/src/ball.h b/src/ball.h index 896b89a..7fd3dd3 100644 --- a/src/ball.h +++ b/src/ball.h @@ -1,6 +1,7 @@ #ifndef BALL_H #define BALL_H +#include "platform.h" #include #include #include @@ -9,7 +10,7 @@ class Ball : public QTimer { Q_OBJECT public: - Ball(QWidget* parent); + Ball(QWidget* parent, std::shared_ptr platform); void draw(QPainter& painter); @@ -21,6 +22,7 @@ class Ball : public QTimer { private: QWidget* m_parent; + std::shared_ptr m_platform; double m_x; double m_y; double m_kx; diff --git a/src/mainwindow.cpp b/src/mainwindow.cpp index b27d935..727ca61 100644 --- a/src/mainwindow.cpp +++ b/src/mainwindow.cpp @@ -9,7 +9,7 @@ MainWindow::MainWindow(QWidget* parent) : QMainWindow(parent), ui(new Ui::MainWi platform = std::make_shared(this); - auto ball = std::make_shared(this); + auto ball = std::make_shared(this, platform); connect(ball.get(), &Ball::deleted, this, &MainWindow::onDeleteBall); balls.append(ball); } diff --git a/src/platform.cpp b/src/platform.cpp index 5037a03..2aa95de 100644 --- a/src/platform.cpp +++ b/src/platform.cpp @@ -19,8 +19,7 @@ Platform::Platform(MainWindow* parent) : m_parent{parent} { } void Platform::draw(QPainter& painter) { - QRect rct(m_x, m_y, PLATFORM_WIDTH, PLATFORM_HEIGHT); - painter.drawRect(rct); + painter.drawRect(rect()); } void Platform::timerEvent(QTimerEvent*) { @@ -34,3 +33,7 @@ void Platform::timerEvent(QTimerEvent*) { m_x += direction * SPEED; } + +QRect Platform::rect() const { + return QRect(m_x, m_y, PLATFORM_WIDTH, PLATFORM_HEIGHT); +} diff --git a/src/platform.h b/src/platform.h index e2ccdd4..629e1cf 100644 --- a/src/platform.h +++ b/src/platform.h @@ -18,6 +18,8 @@ class Platform : public QTimer { void draw(QPainter& painter); + QRect rect() const; + protected: virtual void timerEvent(QTimerEvent*) override;