简体   繁体   中英

Collision Detection of Circle and Rectangle

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

You had a few glitches in your collision function.

Here's working code to detect rectangle vs circle collisions:

function collisionDetection(player,rect){
    var distX = Math.abs(circle.x - rect.x - rect.w/2);
    var distY = Math.abs(circle.y - rect.y - rect.h/2);

    if (distX > (rect.w/2 + circle.r)) { return false; }
    if (distY > (rect.h/2 + circle.r)) { return false; }

    if (distX <= (rect.w/2)) { return true; } 
    if (distY <= (rect.h/2)) { return true; }

    // also test for corner collisions
    var dx=distX-rect.w/2;
    var dy=distY-rect.h/2;
    return (dx*dx+dy*dy<=(circle.r*circle.r));
}

You should not be using width over 2 and height over 2.

You should check of the player.x and player.y are inside the rectangle + the radius. Essentially enlarge all sides of the rectangle by the radius.

rect.y + rect.h + player.r
rect.x + rect.w + player.r
rect.x - player.r
rect.y - player.r

if the player's position is inside the new enlarged rect there is a collision.

if(player.x > (rect.x - player.r) and player.x < (rect.x + rect.w + player.r) and player.y >  (rect.y - player.r) and player.y < rect.y + rect.h + player.r)
return true;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM