Java Circle to Circle collision detection

一个人想着一个人 提交于 2019-12-06 00:04:03

So much uncommented code!

The balls are just colliding if their centres are within the sum of the radii. Let r1 and r2 be the ball radii, and x1, y1 the position of the centre of ball1; similarly x2, y2 for ball2.

Measure the square of the distance between the centres as (x2 - x1) * (x2 - x1) + (y2 - y1) * (y2 - y1). (Pythagoras).

They have collided if this is less than or equal to (r1 + r2) * (r1 + r2).

The key thing here is that there is no need to compute the square roots which is an expensive computational task.

I'd say it probably due to your circles moving too fast or your time step is too high. Reduce your time step. A better approach is use a physics library like Box2D. Have a look at libgdx, that a java library that has it included. its discussed a bit in this link

You should check the colision after each move.

for (int i = 0; i < obj.size(); i++)
{
    obj.get(i).move();

    for (int j = 0; j < obj.size(); j++)
    {
        if (Math.sqrt(Math.pow((double)obj.get(i).centerCoordX - (double)obj.get(j).centerCoordX,2)) + 
                Math.pow((double)obj.get(i).centerCoordY - (double)obj.get(j).centerCoordY,2) <= obj.get(i).radius + obj.get(j).radius && i!=j)
         {
              timer.stop();
         }              
     }
  }

You need something like this.

public boolean overlaps (Circle c1, Circle c2) {
    float dx = c1.x - c2.x;
    float dy = c1.y - c2.y;
    float distance = dx * dx + dy * dy;
    float radiusSum = c1.radius + c2.radius;
    return distance < radiusSum * radiusSum;
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!