球碰撞js公式

时间:2017-06-15 07:07:40

标签: javascript physics

据我所知,矩形的碰撞计算如下:

((a.y + a.height) < (b.top)) ||
(a.y > (b.y + b.height)) ||
((a.x + a.width) < b.x) ||
(a.x > (b.x + b.width))

我希望公式计算两个圆是否发生碰撞。

由于

2 个答案:

答案 0 :(得分:1)

计算它们之间的距离。然后,如果距离小于它们的半径之和,则它们会发生碰撞。

答案 1 :(得分:0)

    // calculates distance between two points
    function distance (p0, p1) {

              var dx = p1.x - p0.x,
                  dy = p1.y - p0.y;
              return Math.sqrt(dx * dx + dy * dy);
          }

    // if the distance between the points is less then or equal to the sum of radii 
    // it returns true i.e collision else false
    function circleCollision (c0, c1) {

              return distance(c0, c1) <= c0.radius + c1.radius;
          }