如何在Android中对位图进行简单的碰撞检测

时间:2013-06-30 16:19:10

标签: android collision-detection android-canvas bitmapfactory

我已经有一个碰撞的代码,但它检查了我并不真正需要的获胜者和ontouch方法,因为我的位图正在移动,我只是希望它们在重叠时发生碰撞。

private boolean checkCollision(Grafika first, Grafika second) {
        boolean retValue = false;

        int width = first.getBitmap().getWidth();
        int height = first.getBitmap().getHeight();

        int x1start = first.getCoordinates().getX();

        int x1end = x1start + width;

        int y1start = first.getCoordinates().getY();

        int y1end = y1start + height;

        int x2start = second.getCoordinates().getX();

        int x2end = x2start + width;

        int y2start = second.getCoordinates().getY();

        int y2end = y2start + height;

        if ((x2start >= x1start && x2start <= x1end) || (x2end >= x1start && x2end <= x1end)) {


            if ((y2start >= y1start && y2start <= y1end) || (y2end >= y1start && y2end <= y1end)) {
                retValue = true;
            }
        }
        return retValue;
    }

1 个答案:

答案 0 :(得分:0)

如果你想要的是找到2个给定的矩形是否以某种方式相交(并因此发生碰撞),这里是最简单的检查(C代码;随意使用浮点值):

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
}

矩形A和B由其角的最小和最大X和Y坐标定义。

相关问题