Home > Mobile >  How would I detect collision on a canvas?
How would I detect collision on a canvas?

Time:10-22

    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 then this is the part I really need help with: detecting if the ball hits the paddle, I have the X part done I just need to finish the Y part and i just can't figure out how. I've experimented many times. Thank you!

    
function checkCollision(){
 if (ball.x <= 45){
  // unfinished, please help I cannot find out how to do the y part
  ball.leftorright = 1
 }
 if (ball.x >= canvas.width - 65){
    // again unfinished, please help I cannot find out how to do the y part
  ball.leftorright = 0
 }
}

CodePudding user response:

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)

CodePudding user response:

You should check if ball.x equals the x edge of each paddle, and then check if ball.y is between paddle.y and paddle.y PADDLE_HEIGHT

function checkCollision(){
  // PADDLE 1
  if (ball.x === paddle1.x   PADDLE_WIDTH && (ball.y >= paddle1.y && ball.y <= paddle1.y   PADDLE_HEIGHT )) {
    // HIT PADDLE 1
    ball.leftorright = 1
  }

  // PADDLE 2
  if (ball.x === paddle2.x && (ball.y >= paddle2.y && ball.y <= paddle2.y   PADDLE_HEIGHT )) {
    // HIT PADDLE 2
    ball.leftorright = 0
  }
}

To check for goals:

if (ball.x > canvas.width) {
  // PLAYER 1 SCORES
}

if (ball.x < 0) {
  // PLAYER 2 SCORES
}
  • Related