Handle ball collisions against platform

This commit is contained in:
ItsDrike 2025-03-24 14:13:16 +01:00
parent 9b458a1eec
commit adaa571b28
Signed by: ItsDrike
GPG key ID: FA2745890B7048C0
5 changed files with 17 additions and 5 deletions

View file

@ -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> 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;

View file

@ -1,6 +1,7 @@
#ifndef BALL_H
#define BALL_H
#include "platform.h"
#include <QPainter>
#include <QTimer>
#include <qobjectdefs.h>
@ -9,7 +10,7 @@ class Ball : public QTimer {
Q_OBJECT
public:
Ball(QWidget* parent);
Ball(QWidget* parent, std::shared_ptr<Platform> platform);
void draw(QPainter& painter);
@ -21,6 +22,7 @@ class Ball : public QTimer {
private:
QWidget* m_parent;
std::shared_ptr<Platform> m_platform;
double m_x;
double m_y;
double m_kx;

View file

@ -9,7 +9,7 @@ MainWindow::MainWindow(QWidget* parent) : QMainWindow(parent), ui(new Ui::MainWi
platform = std::make_shared<Platform>(this);
auto ball = std::make_shared<Ball>(this);
auto ball = std::make_shared<Ball>(this, platform);
connect(ball.get(), &Ball::deleted, this, &MainWindow::onDeleteBall);
balls.append(ball);
}

View file

@ -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);
}

View file

@ -18,6 +18,8 @@ class Platform : public QTimer {
void draw(QPainter& painter);
QRect rect() const;
protected:
virtual void timerEvent(QTimerEvent*) override;