Collision Detection is often used in games. General game engines also carry their own collision detection classes, but sometimes they are not flexible. At this time, we hope we can customize some collision detection classes. Top Tong...
Import Android. Graphics. rect;
Public class collisionutil {
/**
* The rectangle collision detection parameter is X, Y, width, and height.
*
* @ Param X1
* X of the first rectangle
* @ Param Y1
* Y of the first rectangle
* @ Param W1
* W of the first rectangle
* @ Param H1
* H of the first rectangle
* @ Param X2
* X of the second rectangle
* @ Param Y2
* Y of the second rectangle
* @ Param W2
* W of the second rectangle
* @ Param H2
* H of the second rectangle
* [Url = home. php? MoD = Space & uid = 7300] @ return [/url] collision?
*/
Public static Boolean isrectcollision (float X1, float Y1, float W1,
Float H1, float X2, float Y2, float W2, float H2 ){
If (X2> X1 & X2> X1 + W1 ){
Return false;
} Else if (X2 <X1 & X2 <x1-W2 ){
Return false;
} Else if (Y2> Y1 & Y2> Y1 + H1 ){
Return false;
} Else if (Y2 <Y1 & Y2 <Y1-H2 ){
Return false;
} Else {
Return true;
}
}
/**
* The rectangle collision detection parameter is a rect object.
*
* @ Param r1
* The first rect object
* @ Param r2
* Second rect object
* @ Return collision?
*/
Public static Boolean isrectcollision (rect R1, rect R2 ){
Return isrectcollision (r1.left, r1.top, r1.right-r1.left, r1.bottom
-R1.top, r2.left, r2.top, r2.right-r2.left, r2.bottom
-R2.top );
}
/**
* Round Collision Detection
*
* @ Param X1
* The center of the first circle X
* @ Param Y1
* Y of the center of the first circle
* @ Param r1
* Radius of the first circle
* @ Param X2
* The center of the second circle X
* @ Param Y2
* Y of the center of the second circle
* @ Param r2
* Radius of the second circle
* @ Return collision?
*/
Public static Boolean iscirclecollision (INT X1, int Y1, int R1, int X2,
Int Y2, int R2 ){
// The distance between the two points and the radius of the circle is greater than 2
If (math. SQRT (math. Pow (x1-X2, 2) + math. Pow (Y1-Y2, 2)> R1 + R2 ){
Return false;
}
Return true;
}
/**
* Circular and rectangular Collision Detection
*
* @ Param X1
* X of the first rectangle
* @ Param Y1
* Y of the first rectangle
* @ Param W1
* Width of the first rectangle
* @ Param H1
* Height of the first rectangle
* @ Param X2
* Circle center x
* @ Param Y2
* Circle center y
* @ Param r2
* Circle radius R
* @ Return collision?
*/
Public static Boolean isc2rcollision (INT X1, int Y1, int W1, int H1,
Int X2, int Y2, int R2 ){
If (math. Abs (x2-(X1 + W1/2)> W1/2 + R2)
| Math. Abs (Y2-(Y1 + H1/2)> H1/2 + R2 ){
Return false;
}
Return true;
}
/**
* Multi-rectangle collision
*
* @ Param rarray1
* @ Param rarray2
* @ Return collision?
*/
Public static Boolean isrectscollision (rect [] rarray1, rect [] rarray2 ){
For (rect rt1: rarray1 ){
For (rect rt2: rarray2 ){
If (isrectcollision (rt1, rt2 )){
Return true;
}
}
}
Return false;
}
}