I am coding a game that involves the collision of a moving circle, controlled by the user, and a moving rectangle, controlled by the computer.
Full code can be found here: Game
I am having trouble with collision detection between the circle and the rectangle. When the rectangle is static, the collision detection works perfectly. The moment the edges of the circle and rectangle touch on any side, the program acts the way it is supposed to.
However, whenever I give the rectangle motion, the collision works fine on the right side of the rectangle, but not on the left.
I can play with the numbers to make it work on the left but not on the right, however, I can't get it to work correctly on both sides. Is there a simple fix I'm missing?
I have attached a few photos to illustrate what I mean.
This is the collision detection function.
function collisionDetection(player,rect) {
var distX = Math.abs(player.x - player.dx - rect.x - rect.w/2);
var distY = Math.abs(player.y - rect.y - rect.h/2);
if (distX >= (rect.w / 2 + player.r - player.dx)) {
return false;
}
if (distY > (rect.h / 2 + player.r)) {
return false;
}
if (distX <= rect.w/2) {
return true;
}
if (distY <= rect.h/2) {
return true;
}
}
if(collisionDetection(player,rect)) {
alert("You Lose");
document.location.reload();
}
Thank you