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 current X and Y position, and the bitmap height and width. Which is the simplest way to do this?
I have this code:
public void getCollision(Entity enitityOne, Entity enitityTwo){
double eventCoordX = (enitityOne.getCenterX() - (enitityTwo.getBitmapWidth() / 2));
double eventCoor开发者_开发百科dY = (enitityOne.getCenterY() - (enitityTwo.getBitmapHeight() / 2));
double X = Math.abs(enitityTwo.getxPos() - eventCoordX);
double Y = Math.abs(enitityTwo.getyPos() - eventCoordY);
if(X <= (enitityTwo.getBitmapWidth()) && Y <= (enitityTwo.getBitmapHeight())){
enitityOne.collision();
enitityTwo.collision();
}
}
But I'm pretty blind, this only works in the middle of the paddle not on the sides. The problem is I can't see where the code is wrong. Anybody? Anybody have a better idea?
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):
int RectsIntersect(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
{
return 0; // A and B don't intersect
}
return 1; // 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.
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...
精彩评论