Simple Collision Detection - Android
I want to do really simple collision detection in a pong like game. The ball is a square and the paddle (bats) is rectangles. I have two entities coming in where I can get the curr
Solution 1:
If all you want is to find whether or not 2 given rectangles somehow intersect (and therefore collide), here's the simplest check (C code; feel free to use floating-point values):
intRectsIntersect(int AMinX, int AMinY, int AMaxX, int AMaxY,
int BMinX, int BMinY, int BMaxX, int BMaxY)
{
assert(AMinX < AMaxX);
assert(AMinY < AMaxY);
assert(BMinX < BMaxX);
assert(BMinY < BMaxY);
if ((AMaxX < BMinX) || // A is to the left of B
(BMaxX < AMinX) || // B is to the left of A
(AMaxY < BMinY) || // A is above B
(BMaxY < AMinY)) // B is above A
{
return0; // A and B don't intersect
}
return1; // A and B intersect
}
The rectangles A and B are defined by the minimum and maximum X and Y coordinates of their corners.
Um... This has been asked before.
Solution 2:
if you are dealing with rectangles then
/**
* Check if two rectangles collide
* x_1, y_1, width_1, and height_1 define the boundaries of the first rectangle
* x_2, y_2, width_2, and height_2 define the boundaries of the second rectangle
*/boolean rectangle_collision(float x_1, float y_1, float width_1, float height_1, float x_2, float y_2, float width_2, float height_2){
return !(x_1 > x_2+width_2 || x_1+width_1 < x_2 || y_1 > y_2+height_2 || y_1+height_1 < y_2);
}
this is a good example...
Post a Comment for "Simple Collision Detection - Android"