0

我已经有一个碰撞代码,但它检查了我并不真正需要的获胜者和 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;
    }
4

1 回答 1

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 坐标定义。

于 2013-06-30T16:43:46.610 回答