Assuming you are using the ARGB format the highest 8 bits represent the alpha (transparency) channel.
Pixel Perfect Collision
public class RectanglePixelCollisionChecker implements CollisionChecker {
private static final RectangleCollisionChecker RECTANGLE_COLLISION_CHECKER = new RectangleCollisionChecker();
/*
ax,ay ___________ax + a.width
| |
| |
| bx, by_________|__ bx + b.width
| |(INTERSECTION)| |
|__|______________| |
ay + height |
|______________________|
by + height
*/
@Override
public boolean collide(Collidable collidable, Collidable collidable2) {
// check if bounding boxes intersect
if(!RECTANGLE_COLLISION_CHECKER.collide(collidable, collidable2)) {
return false;
}
// get the overlapping box
int startX = Math.max(collidable.getX(), collidable2.getX());
int endX = Math.min(collidable.getX() + collidable.getWidth(), collidable2.getX() + collidable2.getWidth());
int startY = Math.max(collidable.getY(), collidable2.getY());
int endY = Math.min(collidable.getY() + collidable.getHeight(), collidable2.getY() + collidable2.getHeight());
for(int y = startY ; y < endY ; y++) {
for(int x = startX ; x < endX ; x++) {
// compute offsets for surface
if((!isTransparent(collidable2.getBufferedImage(), x - collidable2.getX(), y - collidable2.getY()))
&& (!isTransparent(collidable.getBufferedImage(), x - collidable.getX(), y - collidable.getY()))) {
return true;
}
}
}
return false;
}
private boolean isTransparent(BufferedImage bufferedImage, int x, int y) {
int pixel = bufferedImage.getRGB(x, y);
if((pixel & 0xFF000000) == 0x00000000) {
return true;
}
return false;
}
}
Rectangle Collision
public class RectangleCollisionChecker implements CollisionChecker {
@Override
public boolean collide(final Collidable c1, Collidable c2) {
if((c1.getX() + c1.getWidth() < c2.getX()) || (c2.getX() + c2.getWidth() < c1.getX())) {
return false;
}
if((c1.getY() + c1.getHeight() < c2.getY()) || (c2.getY() + c2.getHeight() < c1.getY())) {
return false;
}
return true;
}
}
Collidable Interface
public interface Collidable {
boolean collide(Collidable collidable);
int getX();
int getY();
int getWidth();
int getHeight();
BufferedImage getBufferedImage();
}