2

I'm making a Breakout game in C++ using the SFML library, I have a "paddle" class as well as a "ball" class, both being updated and rendered in a "game" class, which uses a render window from a "window" class.

My issue is that in order to determine whether the Ball object has collided with the Paddle object, I obviously need access to the Paddle object's x/y position data members. I'm using an update (or tick) function for each object, I'd rather not just pass a reference to the Paddle object into the Ball's update function.

What is the general accepted way to do achieve my desired functionality?

Here is my Ball header:

class Ball
{
public:
    Ball(float x, float y, int size, sf::Vector2f moveSpeed);
    ~Ball();

    void Tick();
    void Move();
    void Render(sf::RenderWindow& window);
    void Reset();

    sf::Vector2f GetMoveSpeed() { return m_moveSpeed; }

private:
    void CheckCollision();

    int m_size;
    sf::Vector2f m_moveSpeed;
    sf::Vector2f m_position;
    sf::CircleShape m_ballCircle;
};

Here is my Game update function:

void Game::Update()
{
    m_window.Update();
    m_ball.Tick();
    m_paddle.Tick();
}
JackMills
  • 21
  • 1
  • 1
    Sounds like your game should be checking if any of your objects collide and then dealing with them appropriately. Neither your paddle or ball will ever know about each other. – UKMonkey Mar 09 '18 at 11:44

2 Answers2

1

Use separate object which implements algorithm for updating ball. This object knows about all your data: ball and paddle, and calculates new position.

You can inject algorithm into your game class, which would hold pointer to interface. This allows you to change algorithm without changing Game, Ball or Paddle classes.

Yola
  • 18,496
  • 11
  • 65
  • 106
0

Let your Game check collision and handle them appropriately:

void Game::Update()
{
    m_window.Update();
    m_ball.Tick();
    m_paddle.Tick();

    if(areColliding(m_ball, m_paddle))
    {
        resolveCollision(m_ball, m_paddle);
    }
}

In this case, areColliding and resolveCollision could be private member functions of Game.

Vittorio Romeo
  • 90,666
  • 33
  • 258
  • 416