1
votes

I'm trying to make a game of Pong. I have drawn everything to screen, bounce the ball of the walls, and have made sure the paddle can only be in the map. The one problem I am having is with collision detection. The algorithm I am using works great if the ball (which is actually a square) hits the paddle in the middle without having any part of the ball hanging off the edge of the paddle. If the ball hits the corner of the paddle or some of the ball hangs off the paddle then the ball glitches into the paddle and does not bounce back. This is my algorithm...

bool CheckCollision(float Ax,float Ay,float Aw,float Ah,float Bx,float By,
float Bw,float Bh) {
    if(Ax>Bx+Bw) {
        return(false);
    }else if(Ax+Aw<Bx) {
        return(false);
    }else if(Ay>By+Bh) {
        return(false);
    }else if(Ay+Ah<By) {
        return(false);
    }
    return(true);
} 

the A and the B represent to different objects and the x, y, w, and h stands for x pos, y pos, width, and height of that specific object. On the receiving end I have...

if(CheckCollision(ball->x,ball->y,ball->width,ball->height,paddle->x,paddle->y,
paddle->width,paddle->height)) {
    ball->vellx = -ball->vellx;
}

This works as I said if the ball hits the paddle in the middle.

If you understood this (as I know that I am not the best with words) is there any way that I can have it so that the ball does not glitch into the paddle? If not, is there another algorithm I can use? Keep in mind this is only 2D.

This is a screenshot of what is happening

http://gyazo.com/920d529217864cca6480a91b217c9b61

As you can see the ball has no collision on the very sides of it, just the points.

I hope this helps

1
Perhaps you can try a smaller timestep?user406009
No, unfortunately that didn't work. The ball seems to go into the paddle whenever the paddle runs into the ball or the paddle moves just as the ball is touching it.Jake Runzer
I still think implementing a ray collision solution would be best.james82345

1 Answers

1
votes

ball->vellx = -ball->vellx;

That's incorrect.

When collision is detected, you need to invert (x) velocity only if ball moves towards paddle. If ball already moves away from paddle, do nothing, and do not modify velocity.

If you'll blindly invert velocity during every collision, ball will get stuck in paddle.

P.S. There are some other things you could tweak (like making ball properly bounce against the corners, adjusting ball speed based on paddle velocity, etc), but that's another story...