圆和矩形的碰撞检测 [英] Collision Detection of Circle and Rectangle

查看:105
本文介绍了圆和矩形的碰撞检测的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在编写一个游戏,其中涉及用户控制的运动圆和计算机控制的运动矩形的碰撞.

完整代码可在此处找到:

谢谢

解决方案

您的碰撞函数有一些小故障.

以下是用于检测矩形与圆形碰撞的工作代码:

 函数crashDetection(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)){返回false;}if(distY>(rect.h/2 + circle.r)){返回false;}if(distX< =(rect.w/2)){返回true;}if(distY< =(rect.h/2)){返回true;}//还测试拐角碰撞var dx = distX-rect.w/2;var dy = distY-rect.h/2;return(dx * dx + dy * dy <=(circle.r * circle.r));} 

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));
}

这篇关于圆和矩形的碰撞检测的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆