Please tell me the code for determining the collision between a rectangle and a circle.

Asked 2 years ago, Updated 2 years ago, 112 views

I'd like to write a program for determining the collision between a rectangle and a circle in a 2D game, so please tell me how to calculate it.
Enter a description of the image here

Let the center of the rectangle be P0, half the width be w/2, and half the length be h/2.
The center of the circle is P1, and the radius is r.

Please tell me the algorithm and code that uses these parameters to determine whether a circle and a rectangle intersect.A rectangle is always parallel to its axis.

algorithm game-development

2022-09-30 18:30

1 Answers

No language is specified, so only algorithms are indicated.

If you omit the detailed explanation in the figure below and conclude, it can be considered a collision when the center P1 of the circle enters the solid line drawn outside the rectangle (red).The light blue line corresponds to the distance r from the outer edge of the rectangle.Therefore, the corners are parallel to the rectangle, and the corners are 1/4 of the circle with radius r.

contact line

Also, please refer to the diagram below to determine if it has entered this light blue solid line.The algorithm shown here is one example, and there are other ways to build it.Also, the decision algorithm shown here is far from fast.An improvement could be to detect contact early.

Enter a description of the image here

There is no additional explanation for 1.Simply calculate and determine the coordinates of the four corners of the yellow area.

2 is divided into two areas, but the yellow area and the overlapping area are assumed to be orange and can be determined as one rectangle.The rest is the same as 1 and there is nothing to explain.

For 3, you can determine from one of the four angles of the red rectangle that is within the distance r.It's just a simple distance calculation, so I'll skip the detailed explanation.

That's all.


2022-09-30 18:30

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.