2
votes

Ive just starded with SFML 2.1 and I wanted to make a Pong game. But I have hit a problem, I cant manage to make a collision detection. When it detects an collision the ball moves to another position even though it dosent stand anywhere. Heres the code you need(Sorry for bad english it isnt my mother tongue):

bool Game::collision()
{
    if (mPlayer.getGlobalBounds().intersects(mBall.getGlobalBounds()))
    {
        mBall.setFillColor(sf::Color::Green);
        score++;
        std::cout << score << std::endl;
        return true;
    }
    else
        return false;
}
void Game::update(sf::Time deltaTime)
{
    sf::Vector2f movement(0.f, 0.f);

    if (mIsMovingLeft)
        movement.x -= PlayerSpeed;
    if (mIsMovingRight)
        movement.x += PlayerSpeed;

    sf::Vector2f gravity(0.f, 4.f);

    mPlayer.move(movement * deltaTime.asSeconds());

    mBall.move(gravity);

    if (collision() == true) {
        mBall.setFillColor(sf::Color::Green);
    }
}
void Game::render()
{
    mWindow.clear(sf::Color::White);
    mWindow.setFramerateLimit(60);
    mWindow.draw(mPlayer);
    mWindow.draw(mBall);
    mWindow.display();
}
1
I somehow cannot grasp this. 1) Does mPlayer represent player paddle? If yes, why do you add score on intersection? Is this some weird dialect of Pong? :D 2) On intersection, you should "correct" the ball to be right next to the paddle. Ball shouldn't go through the paddle, right? You should alter the ball vector of movement as well. Alter it on paddle-ball collision 3) You're setting ball color twice, first in collision(), then in update() 4) Pong and gravity? How does that work? 5) You don't have to setFrameLimit() each frame. Do it in your c-tor. - sjaustirni
See my answer on Tilemap Collision SFML C++ which might help you see the collision coming instead of checking if the ball collides after having moved it. - Emile Bergeron

1 Answers

-2
votes

You need to make each shape a floatrect:

sf::floatrect mBallCollide;
sf::floatrect mplayerCollide;

and then every time they transform set the float rect to them:

mBallCollide = mBall.getGlobalBounds();
mPlayerCollide = mBall.getGlobalBounds();

and then to test for collisions use:

if(mBallCollide.intersects(mPlayerCollide))