我目前正在尝试理解每像素碰撞检测.
这是我不明白的代码:
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;
}
Run Code Online (Sandbox Code Playgroud)
我真的没有理解全部循环.我很乐意解释它是如何工作的.
它不是那么难(在这种情况下) - 你给算法两个对象的边界框(所以洞对象在这个框内),以及一个带有颜色信息的数组.Tha算法假设一个点属于对象IFF它不透明 - 这很重要.
第一步是计算交叉矩形 - 如果你将两个矩形平行于轴的矩形相交,就像这种情况一样 - 你将再次获得一个矩形或一个空集.
下一步是迭代所有(x,y) - 坐标的交叉矩形 - 首先是y,然后是x - 你得到正常的第一个x,然后是y里面,但这是次要点而不重要.
然后最后算法在当前像素(x,y)处获得对象A和B的颜色 - 如果两个颜色都不透明,则像素在两个对象中并且对象必须在此处相交 - 因此算法终止于"是的,他们相交"
如果在检查的边界框的交叉点中的所有像素都没有找到共同(例如,不透明)像素,则该对象不相交,因此算法终止于"否则它们不相交"
我希望这有帮助.
| 归档时间: |
|
| 查看次数: |
5973 次 |
| 最近记录: |