I set the coordinates of the circle and give it a radius of 100. Then I create a similar second circle. When they approach each other and collide, the distance between the centers of mass of the circles must be less than or equal to the sum of the radii. But in fact, the event is triggered, that sumOfRadiuses > distanceBetweenCenterOfMass , but in fact in the picture it is clearly visible that they are far from each other.

I suspect the problem is in radius. For example, java doc:

 public abstract void fillOval(int x, int y, int width, int height) width - the width of the oval to be filled. height - the height of the oval to be filled. 

How does it then interpret this width? And then how to convert then, so that the calculations were accurate?

  • one
    > How does it then interpret this width? As far as I understand, this is the width and height, i.e. there is a certain rectangle, given by the given parameters, into which the oval fits. x, y - top left, width, height - size. - IVsevolod
  • Now it is clear. Otherwise I assumed that these were radii. - nullptr

1 answer 1

I will try to assume that width / height is the diameter (and you consider it as a radius). Accordingly, (x, y) - coordinates of the upper left corner.

Thus, we have the following code:

 class Circle { double centerX; double centerY; double radius; public virtual void draw(Graphics graphics) { int topleftX = (int)Math.round(centerX - radius); int topleftY = (int)Math.round(centerY - radius); int bottomrightX = (int)Math.round(centerX + radius); int bottomrightY = (int)Math.round(centerY + radius); int width = bottomrightX - topleftX; int height = bottomrightY - topleftY; graphics.fillOval(topleftX, topleftY, width, height); } boolean hasCollision(Circle other) { double dx = centerX - other.centerX; double dy = centerY - other.centerY; double distance = Math.sqrt(dx * dx + dy * dy); return distance <= radius + other.radius; } } 

The idea should work.

  • It works, thanks! - nullptr
  • @nullptr: please! - VladD