Skip to content
Advertisement

(self-answered) How would I detect collision on a canvas between a ball and a paddle?

let paddle1 = {
    x: 0,
    y: canvas.height / 2 - PADDLE_HEIGHT / 2,
};

let paddle2 = {
    x: canvas.width - PADDLE_WIDTH,
    y: canvas.height / 2 - PADDLE_HEIGHT / 2,
};

let ball = {
    x: canvas.width / 2,
    y: canvas.height / 2,
    leftorright: Math.round(Math.random()),
    upordown: Math.round(Math.random()),
}; 

is the paddles & ball and the part I really need help with detecting if the ball hits the paddle. What I was trying to do is check the X and the Y to see if it was between the top of the paddle and the bottom, but it wouldn’t work.

function checkCollision() {
  if (ball.x <= 45) {
    // I tried to check the x and the y here but couldn't figure out how
    ball.leftorright = 1
  }
  if (ball.x >= canvas.width - 65) {
    ball.leftorright = 0
  }
}

Advertisement

Answer

In order to find collision between two objects (say paddle and ball), make sure the x position of the right hitbox edge of ball is to the right of the left edge of paddle (ball.x + BALL_WIDTH > paddle.x), its left hitbox edge is to the left of paddle‘s right edge (ball.x < paddle.x + PADDLE_WIDTH), the bottom of ball is below the upper edge of paddle (ball.y + BALL_HEIGHT > paddle.y), and finally the top of ball is above the lower edge of the paddle (ball.y < paddle.y + PADDLE_HEIGHT).

I can’t figure out which side of the board the paddle is on, so remove whichever one is a given (say if it’s on the left, we know for sure it can’t collide below the upper edge in a useful manner, and it would be better just to let it clip through and lose)

User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement