Hi everybody.
Right now I'm just working on a pong game. So far I have the ball bouncing off the top and bottom of the screen implemented, along with scoring for the player and opponent. But I'm having some trouble with the paddle collision. I tried this:
if (ball.getPosition().x > player.getPosition().x &&
ball.getPosition().x < (player.getPosition().x + PADDLE_WIDTH) &&
ball.getPosition().y > player.getPosition().y &&
ball.getPosition().y < (player.getPosition().y + PADDLE_HEIGHT))
{
ballDirX = 1;
if (ballDirY == 1)
ballDirY = -1;
else
ballDirY = 1;
}
But I realized that this only checks if ONE POINT on the ball is colliding with the player's paddle, which causes problems when the player only hits part of the ball that isn't being checked for collisions. How could I implement a collision system that doesn't have these problems?
Quick question actually, how do I use this?
sf::Vector2f pos = Object.TransformToGlobal(sf::Vector2f(0, 0));
I can't find a transformToGlobal function anywhere. Am I missing something?
Ok, so I implemented the bounding box collision system and it works, but I want to split it up so that I can tell whether the ball collides with the top or bottom half of the paddle. This is the boundingboxtest function, how can i modify it to check if it's colliding with the top or bottom half?
int boundingBoxTest(const sf::RectangleShape& object1, const sf::RectangleShape& object2)
{
// 0 = not colliding
// 1 = colliding with top
// 2 = colliding with bottom
BoundingBox obj1 = object1;
BoundingBox obj2 = object2;
// Create the four distinct axes that are perpindicular to the edjes of the two rectangles
sf::Vector2f axes[4] =
{
sf::Vector2f(obj1.points[1].x - obj1.points[0].x, obj1.points[1].y - obj1.points[0].y),
sf::Vector2f(obj1.points[1].x - obj1.points[2].x, obj1.points[1].y - obj1.points[2].y),
sf::Vector2f(obj2.points[0].x - obj2.points[3].x, obj2.points[0].y - obj2.points[3].y),
sf::Vector2f(obj2.points[0].x - obj2.points[1].x, obj2.points[0].y - obj2.points[1].x)
};
for (int i = 0; i < 4; i++)
{
float minOBJ1, maxOBJ1, minOBJ2, maxOBJ2;
obj1.projectOntoAxis(axes[i], minOBJ1, maxOBJ1);
obj2.projectOntoAxis(axes[i], minOBJ2, maxOBJ2);
if (!((minOBJ2 <= maxOBJ1) && (maxOBJ2 >= minOBJ1)))
return 0;
}
return 1;
}
That is an extremely simple problem to solve, so please sit down and think about it on your own for a bit.
If you really can't figure it out: Simply check if the ball is above or below the paddle before the collision.
I'm assuming you check if a movement will produce a collision before actually executing the movement (and thus have access to the ball's pre-move position), since otherwise it's impossible to react to the collision properly.