0
votes

I have a question regarding 2d physics in a JavaScript canvas game that I am working on. In my game I am using the following code to detect collision between a ball and a brick (rectangle). The collision code is working, but the ball passes through the object before it disappears, allowing the ball to clip through the brick field and destroy most of the bricks.

In conclusion, how can I make it so that the ball does not clip through the brick field?

Here is the code used for collision detection:

if(this.enabled && 
   ball.x + ball.vx < this.x + BRICK_WIDTH &&
   ball.x + ball.vx + ball.radius > this.x &&
   ball.y + ball.vy < this.y + BRICK_HEIGHT &&
   ball.y + ball.vy + ball.radius > this.y) {
    ball.vy = -ball.vy;
    this.enabled = false;
}

Here is a video of the faulty collision detection

Also if you would like to, you can try it yourself

Notice how the ball slightly passes through the blue bricks?

2
For fast moving objects (like your ball?), you must find the initial collision point of the ball and the brick. You can adapt this previous Q&A that shows how to collision test the leading edge of an object vs an obstacle. - markE

2 Answers

0
votes
if(this.enabled && 
   ball.x + ball.vx - ball.radius < this.x + BRICK_WIDTH &&
   ball.x + ball.vx + ball.radius > this.x &&
   ball.y + ball.vy - ball.radius < this.y + BRICK_HEIGHT &&
   ball.y + ball.vy + ball.radius > this.y) {
    ball.vy = -ball.vy;
    this.enabled = false;
}

You weren't incorporating the ball's radius in two of your distance calculations. I don't have the rest of your code, so you would have to verify if it works.

0
votes

From the corners, during your check, you are adding the radius which is half the diameter. That means during a collision with the top the ball must go half way through the brick to meet the criteria.

try

     ball.y + ball.vy + ball.radius*2 > this.y

also in the other x check as well....