每像素碰撞 - 代码说明

时间:2011-09-03 11:36:51

标签: c# xna

我目前正在尝试了解每像素碰撞检测。

这是我不明白的代码:

static bool IntersectPixels(Rectangle rectangleA, Color[] dataA,
                            Rectangle rectangleB, Color[] dataB)
{
    // Find the bounds of the rectangle intersection
    int top = Math.Max(rectangleA.Top, rectangleB.Top);
    int bottom = Math.Min(rectangleA.Bottom, rectangleB.Bottom);
    int left = Math.Max(rectangleA.Left, rectangleB.Left);
    int right = Math.Min(rectangleA.Right, rectangleB.Right);

    // Check every point within the intersection bounds
    for (int y = top; y < bottom; y++)
    {
        for (int x = left; x < right; x++)
        {
            // Get the color of both pixels at this point
            Color colorA = dataA[(x - rectangleA.Left) +
                                 (y - rectangleA.Top) * rectangleA.Width];
            Color colorB = dataB[(x - rectangleB.Left) +
                                 (y - rectangleB.Top) * rectangleB.Width];

            // If both pixels are not completely transparent,
            if (colorA.A != 0 && colorB.A != 0)
            {
                // then an intersection has been found
                return true;
            }
        }
    }

    // No intersection found
    return false;
}

我真的没有理解全部循环。我很乐意解释它是如何运作的。

3 个答案:

答案 0 :(得分:7)

首先,它找到两个图像矩形相交的区域,然后迭代该区域中的每个像素,并比较每个像素的每个图像的alpha值。如果两者的α值均为0,则它​​们都被认为是“实心”,因此会发生碰撞。

enter image description here

答案 1 :(得分:5)

它并不那么难(在这种情况下) - 你给算法两个对象的边界框(所以洞对象在这个框内),以及一个带有颜色信息的数组。 Tha算法假设一个点属于对象IFF它不透明 - 这很重要。

第一步是计算交叉矩形 - 如果你将两个边长平行于轴的矩形相交,就像这种情况一样 - 你将再次得到一个矩形或一个空集。

下一步是迭代所有(x,y)坐标的交叉矩形 - 首先是y,然后是x - 你得到正常的第一个x,然后是y,但这是次要的,不重要

然后最后算法在当前像素(x,y)处获得对象A和B的颜色 - 如果两种颜色都不透明,那么像素在两个对象中并且对象必须在此处相交 - 所以算法终止于“是的,它们相交”

如果检查到的边界框的交叉点中的所有像素都没有找到共同(例如不透明)像素,则该对象不会相交,因此算法终止于“否则它们不相交”

我希望这会有所帮助。

答案 2 :(得分:0)

for (int y = top; y < bottom; y++)从上到下遍历生成的矩形的线条,for (int x = left; x < right; x++)在每条线内的像素上从左到右循环。