Hi folks, I need your help with collision detection with my little sfml pong game.
First I can detect the collision with walls(window boundaries) however I can't do the same with rackets. I just don't get where the mistake is...
as a background information, my ball is a square.
fallowing lines belong to collision detection function. Firstly I'm trying to understand if ball is going left and did it hit the racket horizontally. Then I control if it's indeed hit the racket by checking the coordinate vertically.
int Ball::detectCollision(Racket &leftRacket, Racket &rightRacket)
{
sf::Vector2f bouncerPosition = geometry_.GetPosition();
sf::Vector2f leftRacketPosition = leftRacket.getRacketPosition();
sf::Vector2f rightRacketPosition = rightRacket.getRacketPosition();
float racketWidth = leftRacket.getRacketWidth();
float racketHeight = leftRacket.getRacketHeight();
if(bouncerPosition.x <= leftRacketPosition.x + racketWidth && velocity_.x < 0.0f)
{
if(bouncerPosition.y + ballHeight_ >= leftRacketPosition.y && bouncerPosition.y <= leftRacketPosition.y + racketHeight)
{
return COLLIDING_WITH_LEFT_PADDLE;
}
}
else if(bouncerPosition.x + ballWidth_ >= rightRacketPosition.x && velocity_.x > 0.0f)
{
if(bouncerPosition.y + ballHeight_ >= rightRacketPosition.y && bouncerPosition.y <= rightRacketPosition.y + racketHeight)
{
return COLLIDING_WITH_RIGHT_PADDLE;
}
}
else
{
return NO_COLLISION;
}
}
and here is my process function for collision. In essence, what I'm trying to do is firstly changing the x velocity and then altering the ball position for possible infinite strucks in paddle.
void Ball::processCollision(const int collisionInformation, Racket &leftRacket, Racket &rightRacket)
{
sf::Vector2f bouncerPosition = geometry_.GetPosition();
sf::Vector2f leftRacketPosition = leftRacket.getRacketPosition();
sf::Vector2f rightRacketPosition = rightRacket.getRacketPosition();
float racketWidth = leftRacket.getRacketWidth();
float fraction = 0.0f;
if(collisionInformation == COLLIDING_WITH_LEFT_PADDLE)
{
velocity_.x = -velocity_.x;
fraction = -(bouncerPosition.x - leftRacketPosition.x + racketWidth);
bouncerPosition.x += fraction;
geometry_.SetPosition(bouncerPosition);
}
else if(collisionInformation == COLLIDING_WITH_RIGHT_PADDLE)
{
velocity_.x = -velocity_.x;
fraction = -(bouncerPosition.x + ballWidth_ - leftRacketPosition.x);
bouncerPosition.x += fraction;
geometry_.SetPosition(bouncerPosition);
}
}
and enumartion for collision types:
enum COLLISION_INFORMATION
{
NO_COLLISION,
COLLIDING_WITH_UPPER_WALL,
COLLIDING_WITH_LOWER_WALL,
COLLIDING_WITH_LEFT_WALL,
COLLIDING_WITH_RIGHT_WALL,
COLLIDING_WITH_LEFT_PADDLE,
COLLIDING_WITH_RIGHT_PADDLE
};
Finally my driving code in the main game loop:
bouncer.calculateDisplacement(deltaTime);
if(collidingEdge = bouncer.detectCollision(leftRacket, rightRacket))
{
bouncer.processCollision(collidingEdge, leftRacket, rightRacket);
bouncer.accelerate();
}
else
{
bouncer.bounce();
bouncer.tailAnimation();
}
}
Thank you in advance!