如何检查一条线上的矩形碰撞

时间:2015-03-20 20:04:52

标签: c# xna collision-detection

我有一条从两个矩形画出的线,从xpos, yposxpos2, ypos2。我试图检测一个矩形(存储在4个X / Y位置和这两个方向的随机速度)是否与该线发生碰撞。

我在(Vector2.Distance(new Vector2(xpos + 13, ypos + 13), new Vector2(EnX[index], EnY[index])) + Vector2.Distance(new Vector2(xpos2 + 13, ypos2 + 13), new Vector2(EnX[index], EnY[index])) == Vector2.Distance(new Vector2(xpos + 13, ypos + 13), new Vector2(xpos2 + 13, ypos2 + 13)))声明中尝试了if,但这不起作用。

编辑:我现在尝试了

        m = (ypos2 + 13 - ypos + 13) / (xpos2 + 13 - xpos + 13);
        b = ((m * xpos2 + 13) - ypos2 + 13);
        if (EnY[index] == m * EnX[index] + b)

其中Xpos / 2和ypos / 2是行起点。 EnX []和EnY []是“敌人”的X和Y位置,我试图检查他们是否正在击中一条线。

1 个答案:

答案 0 :(得分:0)

我假设您将矩形的角位置设为2d向量:

Vector2[] corners;

如果任意两个角点位于线的另一侧,则矩形与线相交。为了评估边线,我们需要线条正常(您尝试的斜率方法可能会因垂直线条而失败):

Vector2 normal = new Vector2D(ypos2 - ypos, xpos - xpos2);

然后我们可以使用点积的符号来评估边:

Vector2 lineStart = new Vector2(xpos, ypos);
//we don't know yet on which side of the line the rectangle lies
float rectangleSide = 0;
foreach(Vector2 corner in corners)
{
    //cornerSide will be positive if the corner is on the side the normal points to,
    //zero if the corner is exactly on the line, and negative otherwise
    float cornerSide = Vector2.Dot(corner - lineStart, normal);
    if(rectangleSide == 0)
        //first evaluated corner or all previous corners lie exactly on the line
        rectangleSide = cornerSide;
    else
        if(cornerSide != 0 && //ignore corners on the line
          (cornerSide > 0) != (rectangleSide > 0)) //different sides
             return true; //rectangle intersects with line
}
return false; //rectangle does not intersect with line