I am making a game for android which I need hit detection between two objects. The first bitmap I have is a flying superhero, and the second bitmap is anything that he collides with.
The superhero bitmap is created on the fly by rotating the original bitmap between -90 and 90 degrees. As a result of the rotation, the bounding box is much, much larger than the non-rotated version. I have code to detect if the bounding box of the player hits any object, but visually this creates a problem when the object comes in contact with the skewed bounding box.
I need a solution that computes pixel-perfect hit detection between the player and the object, not just the bounding boxes.
I have been searching for the past 5 days for examples, tutorials, code snippets, or anything that could help me, but I haven't found a solution. The solution I'm looking for would be simply one function call similar to public boolean(obstacle theobject), where the obstacle's bitmap. coordinates, width, and height are returned with obstacle.getbitmap, obstacle.getx, obstacle.gety, obstacle.getwidth, and obstacle.getheight. The bitmap of the player is named rotatedbm and has global variables playerx, playery, playerh, and playerw.
I do not wish to implement external game engines or libraries.
I have read much on using int arrays with Bitmap.getPixels, and then comparing the arrays, but I cannot grasp the math behind comparing the arrays nor sorting out alpha values. I cannot afford to stay stuck on this one problem much long for the sake of development.
Thank you
EDIT- This is my implementation of the pseudo code. In the log, 'hit true' is never thrown but 'hit trying' is. Its not working as intended...
public boolean gethit(obstacle second){
int px,py,ph,pw;
Bitmap sprite1 = rotatedbm;
Bitmap sprite2 = second.getgfx();
px = playerx;
py = playery;
ph = sprite1.getHeight();
pw = sprite1.getWidth();
int ox = second.obx;
int oy = second.oby;
int oh = second.obh;
int ow = second.obw;
int [] AABB1bl = {px, py+ph};
int [] AABB1tr = {px+pw, py};
int [] AABB2bl = {ox, oy+oh};
int [] AABB2tr = {ox+ow, oy};
AABB2bl[0] -= AABB1bl[0];
AABB2bl[1] -= AABB1bl[1];
AABB2tr[0] -= AABB1bl[0];
AABB2tr[1] -= AABB1bl[1];
AABB1tr[0] -= AABB1bl[0];
AABB1tr[1] -= AABB1bl[1];
AABB1bl[0] -= AABB1bl[0];
AABB1bl[1] -= AABB1bl[1];
int start_x = AABB2bl[0];
int start_y = AABB2tr[1];
int end_x = AABB1tr[0];
int end_y = AABB1bl[1];
int ALPHAMASK = 0xFF<<24; // assuming colors are represented as 0xAARRBBGG
int alpha1;
int alpha2;
Log.i("hit", "trying");
for(int x = start_x; x < end_x; x++)
for(int y = start_y; y < end_y; y++) {
alpha1 = sprite1.getPixel(x , y*sprite1.getWidth()) & ALPHAMASK;
alpha2 = sprite2.getPixel(x + AABB2bl[0], (y+AABB2tr[1])*sprite2.getWidth()) & ALPHAMASK;
if(alpha1 != 0 && alpha2 != 0) {
Log.i("hit", "true");
return true; // you'd probably wish to return after a colliding pixel has been found
}
}
return false;
}