每像素碰撞 – 代码说明

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

这是我不明白的代码:

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

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

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

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

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

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

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

我希望这有帮助。

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

在此处输入图像描述

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