Search code examples
javascriptcanvas2dcollision-detectiongame-physics

How to fix bad 2D collision


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?


Solution

  • 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.