此代码如何执行“每像素碰撞检测”?

问题描述 投票:0回答:3

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

这是我不明白的代码:

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;
}

我真的不明白这些嵌套循环。我很高兴能得到一些关于它如何工作的解释。

c# xna collision-detection intersection bounding-box
3个回答
7
投票

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

enter image description here


5
投票

这并不难(在本例中) - 您为算法提供对象的两个边界框(因此孔对象位于此框内),以及一个包含它们颜色信息的数组。 Tha 算法假设一个点属于对象 IFF 它不是透明的 - 这很重要。

第一步是计算相交矩形 - 如果像本例一样将两个边平行于轴的矩形相交 - 您将再次得到一个矩形或一个空集。

下一步是在这个相交矩形中迭代所有 (x,y) 坐标 - 首先是 y,然后是 x - 这样你就可以得到正常的第一个 x,然后是 y,但这是次要问题,并不重要。

最后,算法在当前像素 (x,y) 处获取对象 A 和 B 的颜色 - 如果两种颜色都不透明,则该像素位于两个对象中,并且对象必须在这一点相交 - 因此算法终止与“是的,他们相交”

如果检查了边界框相交处的所有像素并且未找到公共(例如不透明)像素,则该对象不相交,因此算法以“不,它们不相交”终止

我希望这有帮助。


0
投票

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

© www.soinside.com 2019 - 2024. All rights reserved.