易旋转矩形碰撞

时间:2013-04-14 03:56:43

标签: java awt collision-detection java-2d rectangles

我正在使用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;
}

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

2 个答案:

答案 0 :(得分:2)

如果两个矩形相交,则一个矩形内的一个点也位于另一个矩形内。

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

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

答案 1 :(得分: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;
}