js collision detection

This article explains circles and rectangles in the two-dimensional plane collision
principle

Find the closest center point of the rectangle, calculating the distance to the center point compared with the radius of the circle.

method

First, define the coordinate of the closest point x, y coordinates, the coordinates of the center, the left rectangle and the distance to the upper side of the outer container, the width and height of the rectangle.

var closest_x , closest_y; 
var circle_x ,circle_y;
var rectangle_x , rectangle_y , rectangle_w , rectangle_h;

The first analysis of the x-coordinate of the nearest point

Here Insert Picture Description

When the center of the rectangle on the left
x coordinate of the closest point of the rectangle is the distance of the outer container according to the left.
I.e. closest_x = rectangle_x;

Here Insert Picture Description

When the right side of the center of the rectangular
x-coordinate of the closest point of the rectangle to the left from the outer container + rectangle width.
I.e. closest_x = rectangle_x + rectangle_w;

Here Insert Picture Description

When the center of the rectangle just above or just below.
= X coordinate of the closest point of the x-coordinate of the center
i.e. closest_x = circle_x;

y-axis coordinates of the closest point

X-coordinate analysis and thinking is the same.

Here Insert Picture Description

When the center of the rectangular top
from the y-coordinate of the closest point to the upper side of the rectangle = outer container.
I.e. closest_y = rectangle_y;

Here Insert Picture Description

When the center under the rectangle
y-axis coordinates of the closest point to the upper side of the rectangular outer container = distance + height of the rectangle.
I.e. closest_y = rectangle_y + rectangle_h;

Here Insert Picture Description

When the positive rectangular left and right sides of the center of
the nearest point = y coordinate of the center y coordinate
i.e. closest_y = circle_y;

Such nearest point of x and y coordinates we have found the
final formula obtained by the distance between two points distance compared to the radius of the circle
if the radius of the circle is smaller than it shows collide.


Gentle Reminder:

It is reasonable to use if () {} ... else { } statement to write code to implement the ideas above.
It also did not take long to learn if there is a better way to welcome comments or private letter.

Released four original articles · won praise 5 · Views 115

Guess you like

Origin blog.csdn.net/cmomo99d/article/details/104473780