void testCollision(Paddle& mPaddle, Ball& mBall) { if(!isIntersecting(mPaddle, mBall)) return; mBall.velocity.y = -ballVelocity; if(mBall.x() < mPaddle.x()) mBall.velocity.x = -ballVelocity; else mBall.velocity.x = ballVelocity; }
void solvePaddleBallCollision(const Paddle& mPaddle, Ball& mBall) noexcept { if(!isIntersecting(mPaddle, mBall)) return; mBall.velocity.y = -Ball::defVelocity; mBall.velocity.x = mBall.x() < mPaddle.x() ? -Ball::defVelocity : Ball::defVelocity; }
void solvePaddleBallCollision(const Paddle& mPaddle, Ball& mBall) noexcept { if(!isIntersecting(mPaddle, mBall)) return; auto newY(mPaddle.top() - mBall.shape.getRadius() * 2.f); mBall.shape.setPosition(mBall.x(), newY); auto paddleBallDiff(mBall.x() - mPaddle.x()); auto posFactor(paddleBallDiff / mPaddle.width()); auto velFactor(mPaddle.velocity.x * 0.05f); sf::Vector2f collisionVec{posFactor + velFactor, -2.f}; mBall.velocity = getReflected(mBall.velocity, getNormalized(collisionVec)); }
// Let's define a function that deals with paddle/ball collision. void testCollision(Paddle& mPaddle, Ball& mBall) { // If there's no intersection, get out of the function. if(!isIntersecting(mPaddle, mBall)) return; // Otherwise let's "push" the ball upwards. mBall.velocity.y = -ballVelocity; // And let's direct it dependently on the position where the // paddle was hit. if(mBall.x() < mPaddle.x()) mBall.velocity.x = -ballVelocity; else mBall.velocity.x = ballVelocity; }
// Now, let's also define a function that will executed every game // frame. This function will check if a paddle and a ball are // colliding, and if they are it will resolve the collision by // making the ball go upwards and in the direction opposite to the // collision. void solvePaddleBallCollision(const Paddle& mPaddle, Ball& mBall) noexcept { // If there's no intersection, exit the function. if(!isIntersecting(mPaddle, mBall)) return; // Otherwise let's "push" the ball upwards. mBall.velocity.y = -Ball::defVelocity; // And let's direct it dependently on the position where the // paddle was hit. // If the ball's center was to the left of the paddle's center, // the ball will move towards the left. Otherwise, it will move // towards the right. // {Info: ball vs paddle collision} mBall.velocity.x = mBall.x() < mPaddle.x() ? -Ball::defVelocity : Ball::defVelocity; }