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();
}
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 incollision()
, then inupdate()
4) Pong and gravity? How does that work? 5) You don't have to setFrameLimit() each frame. Do it in your c-tor. - sjaustirni