public boolean isCollision(int thisLeft, int thisTop, int thisRight, int thisBottom, int otherLeft, int otherTop, int otherRight, int otherBottom) {
//如果图片不相交的话,不进行像素碰撞检测
if (thisLeft > otherRight || thisTop > otherBottom || otherLeft > thisRight || otherTop > thisBottom) {
return false;
}
//计算相交区域的矩形的左上角和右下角坐标,以及矩形的宽度和高度
int intersectLeft = thisLeft > otherLeft ? thisLeft : otherLeft;
int intersectTop = thisTop > otherTop ? thisTop : otherTop;
int intersectRight = thisRight < otherRight ? thisRight : otherRight;
int intersectBottom = thisBottom < otherBottom ? thisBottom : otherBottom;
int intersectWidth = intersectRight - intersectLeft;
int intersectHeight = intersectBottom - intersectTop;
//计算图片相对于相交区域的偏移量(每张图片要去的相交区域的ARGB数据,其实最重要的还是取得A)
int thisImageXOffset = intersectLeft - thisLeft;
int thisImageYOffset = intersectTop - thisTop;
int otherImageXOffset = intersectLeft - otherLeft;
int otherImageYOffset = intersectTop - otherTop;
//进行像素碰撞检测
boolean isCollide;
isCollide = doPixelCollision(thisImageXOffset, thisImageYOffset, otherImageXOffset, otherImageYOffset, down, blackHole, intersectWidth, intersectHeight);
return isCollide;
}
//(算法思路:取得两张图片的相交区域的ARBG数据,然后取得的A(透明色)的数据,如果两张图片的A的数
//据都不等于0则说明碰上了)
private boolean doPixelCollision(int firstImageXOffset, int firstImageYOffset, int secondImageXOffset, int secondImageYOffset,
Image firstImage, Image secondImage, int intersectWidth, int intersectHeight) {
int numPixels = intersectHeight * intersectWidth;
int[] argbData1 = new int[numPixels];
int[] argbData2 = new int[numPixels];
firstImage.getRGB(argbData1, 0, intersectWidth, // scanlength = width
firstImageXOffset, firstImageYOffset, intersectWidth, intersectHeight);
secondImage.getRGB(argbData2, 0, intersectWidth, secondImageXOffset, secondImageYOffset, intersectWidth, intersectHeight);
//像素碰撞检测
for (int row = 0; row < intersectHeight; row++) {
for (int col = 0; col < intersectWidth; col++) {
if ((argbData1[row * intersectWidth + col] & 0xff000000) != 0 && (argbData2[row * intersectWidth + col] & 0xff000000) != 0) {
return true;
}
}
}
return false;
}