1

我正在使用 LibGDX 制作游戏,但遇到了有关矩形碰撞检测的问题。

public class Rectangle{
   final float width = 1f;
   final float height = 0.5f;
   Point topLeft;
   Point topRight;
   Point bottomRight;
   Point bottomLeft;  
   //The point of rotation is the middle of the rectangle
   float angle;
}

public class Point{
   float x;
   float y;
}

使用这些信息(所有这些变量都将预先计算),我想计算两个矩形是否完全重叠?

4

2 回答 2

2

如果两个矩形相交,则一个矩形内将有一个点,该点也在另一个矩形内。

您可以将每个矩形视为四条线。要在矩形内,一个点必须位于左线的右侧、右线的左侧、底线上方和顶线下方。因此,矩形可以表示为具有解的四个线性不等式的系统。

如果将一个矩形的四个线性不等式与另一个矩形的四个线性不等式组合成一个八不等式系统,则新系统只有在矩形相交时才有解。

于 2013-04-14T19:51:57.023 回答
1

这是我最终使用的,请注意,我根本不想优化代码。

private boolean isColliding(Point p){
    float countCol = 0f;
    // BottomLeft - BottomRight
    float slope = ((player.getBottomLeft().getY() - player.getBottomRight().getY()) / (player.getBottomLeft().getX() - player.getBottomRight().getX()));
    float intercept = (player.getBottomLeft().getY() - (player.getBottomLeft().getX() * slope));

    // BottomLeft - TopLeft
    float slope2 = ((player.getBottomLeft().getY() - player.getTopLeft().getY()) / (player.getBottomLeft().getX() - player.getTopLeft().getX()));
    float intercept2 = (player.getTopLeft().getY() - (player.getTopLeft().getX() * slope2));

    // TopLeft - TopRight
    float slope3 = ((player.getTopLeft().getY() - player.getTopRight().getY()) / (player.getTopLeft().getX() - player.getTopRight().getX()));
    float intercept3 = (player.getTopRight().getY() - (player.getTopRight().getX() * slope3));

    // TopRight - BottomRight
    float slope4 = ((player.getTopRight().getY() - player.getBottomRight().getY()) / (player.getTopRight().getX() - player.getBottomRight().getX()));
    float intercept4 = (player.getBottomRight().getY() - (player.getBottomRight().getX() * slope4));

    // Between top and bottom
    if(player.getAngle() > -90 && player.getAngle() < 90){
        // BottomLeft - BottomRight
        if(p.getX() * slope + intercept < p.getY()){
            countCol += 1;
        }

        // TopLeft - TopRight
        if(p.getX() * slope3 + intercept3 > p.getY()){
            countCol += 1;
        }
    }
    else{
        // BottomLeft - BottomRight
        if(p.getX() * slope + intercept > p.getY()){
            countCol += 1;
        }

        // TopLeft - TopRight
        if(p.getX() * slope3 + intercept3 < p.getY()){
            countCol += 1;
        }
    }

    // BottomLeft - TopLeft
    if(player.getAngle() < 0){
        if(p.getX() * slope2 + intercept2 > p.getY()){
            countCol += 1;
        }
        if(p.getX() * slope4 + intercept4 < p.getY()){
            countCol += 1;
        }
    }
    else{
        if(p.getX() * slope2 + intercept2 < p.getY()){
            countCol += 1;
        }
        if(p.getX() * slope4 + intercept4 > p.getY()){
            countCol += 1;
        }
    }

    if(countCol >= 4){
        return true;
    }
    return false;
}
于 2013-04-15T00:24:21.180 回答