1
votes

Hi I wrote this simple collision detection and bouncing algorithm but the collision detects the y as if it was the x axis

enter image description here

bool Ball::DetectCollision(Paddle p)
{
if(GetPosition().y >= p.GetPosition().y + p.GetSize().y
|| GetPosition().y + GetSize().y <= p.GetPosition().y
|| GetPosition().x >= p.GetPosition().x + p.GetSize().x
|| GetPosition().x + GetSize().x <= p.GetPosition().x)
{
    return false;
}

if(GetPosition().y <= p.GetPosition().y + p.GetSize().y )
{
    Bounce(-1,1);
}
else if(GetPosition().y + GetSize().x >= p.GetPosition().y)
{
    Bounce(-1,1);
}

else if(GetPosition().x + GetSize().x >= p.GetPosition().x )
{
    Bounce(1,-1);
}
else if(GetPosition().x <= p.GetPosition().x + p.GetSize().x)
{
    Bounce(1,-1);
}


    return true;
}

void Ball::Bounce(int a, int b)
{
    velocity = sf::Vector2f(velocity.x * a,velocity.y * b);
}

at first it seems to be working, the I found out that it only works in one axis (if the ball hits the paddle from it's bottom or top, it doesn't bounce properly and it bouces as if it hit the front surface of the paddle -> ^|)

3

3 Answers

1
votes

Seems to me that the line

else if(GetPosition().y + GetSize().x >= p.GetPosition().y)

should be

else if(GetPosition().y + GetSize().y >= p.GetPosition().y)

Notice the change from GetSize().x to GetSize().y

See if that solves it. Cheers!

0
votes

To add collision detection to the top or bottom of the paddle (assuming you mean the very top or bottom and not front surface), try to change your conditions at the beginning slightly and add a new one at the end.

First, get rid of the equals signs in your beginning condition.

  if(GetPosition().y > p.GetPosition().y + p.GetSize().y
|| GetPosition().y + GetSize().y < p.GetPosition().y
|| GetPosition().x > p.GetPosition().x + p.GetSize().x
|| GetPosition().x + GetSize().x < p.GetPosition().x)
{

Try and add this condition unnested among the end

//Assuming origin at top-left of ball
if((GetPosition().x  + GetSize().y/2 < p.GetPosition().x + p.GetSize() //GetSize().y/2 to point at center
&& GetPosition().x + GetSize().y/2 > p.GetPosition().x) /*if x-cord is between paddle*/
&& (GetPosition().y + getSize() == p.GetPosition().y || 
GetPosition.y == p.GetPosition().y p.getSize())) /*if y-cord touches the top or bottom*/
     Bounce(1,-1); /*Bounce, change y velocity*/

Hopefully this works and I answered your question.

0
votes

When collision happens in y dir the ball should bounce back in y but you do Bounce(-1,1) which actually bounces it in x direction by revrsing x-direction velocity and similiarly for other three cases. You should do

 if((GetPosition().y <= p.GetPosition().y + p.GetSize().y )&& (GetPosition().y >= p.GetPosition().y))
 Bounce(1,-1);