Collision Detection Algorithm: point-and-rectangle collision, point-and-circle collision, rectangular collision, and circular collision
Point and rectangle collision
[Java]
- /**
- *
- * @ Param x1
- * @ Param y1
- * @ Param x2 rectangular view x
- * @ Param y2 rectangular view y
- * @ Param w rectangular view width
- * @ Param h rectangular view height
- * @ Return
- */
- Public static boolean isCollsion (int x1, int y1, int x2, int y2, int w, int h ){
- If (x1> = x2 & x1 <= x2 + w & y1> = y2 & y1 <= y2 + h ){
- Return true;
- }
- Return false;
- }
Rectangular collision
[Java]
- /**
- * Checks whether two rectangles collide.
- * @ Return
- */
- Public boolean isCollsionWithRect (int x1, int y1, int w1, int h1,
- Int x2, int y2, int w2, int h2 ){
- If (x1> = x2 & x1> = x2 + w2 ){
- Return false;
- } Else if (x1 <= x2 & x1 + w1 <= x2 ){
- Return false;
- } Else if (y1> = y2 & y1> = y2 + h2 ){
- Return false;
- } Else if (y1 <= y2 & y1 + h1 <= y2 ){
- Return false;
- }
- Return true;
- }
Point (x1, x2), center (x2, y2), radius r
[Java]
- If (Math. sqrt (Math. pow (x1-x2, 2) + Math. pow (y1-y2, 2) <= r ){
- // If the distance between the vertex and the center is smaller than or equal to the radius, the collision is considered
- Return true;
- }
Circle and circle
[Java]
- /**
- * Round collision
- *
- * @ Param x1
- * X coordinate of the Center of circular 1
- * @ Param y1
- * X coordinate of the Center of Circular 2
- * @ Param x2
- * Y coordinate of the Center of circular 1
- * @ Param y2
- * Y coordinate of the Center of Circular 2
- * @ Param r1
- * Radius of circle 1
- * @ Param r2
- * Radius of circle 2
- * @ Return
- */
- Private boolean isCollisionWithCircle (int x1, int y1, int x2, int y2,
- Int r1, int r2 ){
- // Math. sqrt: Square
- // Math. pow (double x, double y): Power Y of X
- // Cartesian coordinate system, parallel line according to point 1 and point 2, | x1-x2 | for horizontal corner edge, | y1-y2 | for vertical straight angle edge according to the stock Theorem c ^ 2 = a ^ 2 + B ^ 2
- If (Math. sqrt (Math. pow (x1-x2, 2) + Math. pow (y1-y2, 2) <= r1 + r2 ){
- // If the center distance of the two circles is less than or equal to the radius of the two circles and the collision is considered
- Return true;
- }
- Return false;
- }