Brick Breaker Ball Bounce

52 Views Asked by At

I'm trying to make my own Brick Breaker game using SDL library and I'm having some issues with dealing the collision resolution and ball bouncing when it comes to the bouncing of the paddle.

I'm calculating collision angle based on the collision point between ball and paddle and calculating balls' velocity direction based on that angle.

The issue I'm experiencing is after the collision with the paddle, ball doesn't change it's Y direction, instead just keeps going down and hitting the paddle. It continues to do that until eventually "slides" of the paddle.

I don't think my math is wrong here (although it could easily be), but I simply don't know what the issue is or how to fix it.

This is the code that is responsible for collision detection and calculating angle and direction.

void Ball::CollisionWithPaddle(Paddle*& paddle)
{
    if (CollisionManager::GetInstance()->Collision(GetHitbox(), paddle->GetHitbox()))
    {   
        double collisionAngle = CalculateCollisionAngle(paddle->GetHitbox());
        
        Vector2Df newVelocityDirection = CalculateNewVelocityDirection(collisionAngle);  
        velocity = newVelocityDirection * velocity.Magnitude();             

        AdjustBallPosition(paddle);
    }   
}

double Ball::CalculateCollisionAngle(const SDL_Rect& paddle)
{
    double collisionPointX = transform->X + width / static_cast<double>(2);
    double collisionPointY = transform->Y + height / static_cast<double>(2);

    double relativeX = collisionPointX - (paddle.x + paddle.w / static_cast<double>(2));
    double relativeY = collisionPointY - (paddle.y + paddle.h / static_cast<double>(2));

    double collisionAngle = atan2(relativeY, relativeX);

    return collisionAngle;
}

Vector2Df Ball::CalculateNewVelocityDirection(double collisionAngle)
{
    // Calculate direction of the new velocity based on the collision angle
    double newVelocityX = std::cos(collisionAngle);
    double newVelocityY = -std::sin(collisionAngle);

    Vector2Df newVelocityDirection(newVelocityX, newVelocityY);
    
    return newVelocityDirection.Normalize();
}

void Ball::AdjustBallPosition(Paddle* paddle)
{
    transform->Y = paddle->GetHitbox().y - height;  
}

This is the code where I'm simply updating the position of the ball with the current velocity.

void Ball::Update()
{
    transform->X += velocity.X * Engine::GetInstance()->GetDeltaTime();
    transform->Y += velocity.Y * Engine::GetInstance()->GetDeltaTime();

    rec.x = transform->X;
    rec.y = transform->Y;   
}
0

There are 0 best solutions below