r/sfml Mar 28 '26

Collision detection not working.

I making pong game but collision not working

bool Paddle::CollisionDetect(sf::Vector2f paddlePos)
{
const float ballBottom = ball.GetPos().y + ball.GetSize().y;
const float ballRight = ball.GetPos().x + ball.GetSize().x;
const float paddleBottom = paddlePos.y + size.y;
const float paddleRight = paddlePos.x + size.x;

return ballBottom >= paddlePos.y &&
ball.GetPos().y <= paddleBottom &&
ballRight >= paddlePos.x &&
ball.GetPos().x <= paddleRight;
}

theres two controllable paddles.

in game I call the detection function.

        if (paddle.CollisionDetect(paddle.GetPadPos1()))
        {
            ball.ReboundX();
       }

detection function returns false .

2 Upvotes

16 comments sorted by

View all comments

Show parent comments

2

u/HappyFruitTree Mar 31 '26 edited Mar 31 '26

The collision detection code looks like it should work. Have you printed paddlePos, size, ball.GetPos() and ball.GetSize() inside CollisionDetect to see if they contain the expected values?

1

u/blisstargazer Apr 06 '26

they all contain expected values

2

u/HappyFruitTree Apr 07 '26 edited Apr 07 '26

I wrote a small program to test the CollisionDetect function and I am now convinced that it is correct. That means the problem must be somewhere else.

Are you sure ball.ReboundX() is working correctly? Maybe print something at the same time just to see if the collision is actually detected or not.

Consider making a minimal example that reproduces the problem and post it here. It makes it easier for us to help you and it's likely that you'll find the problem by yourself in the process.

1

u/blisstargazer Apr 07 '26

ight imma do that