我试图理解检查游戏中两个对象之间碰撞的代码 - 每像素碰撞。代码是:
/// <summary>
/// Determines if there is overlap of the non-transparent pixels
/// between two sprites.
/// </summary>
/// <param name="rectangleA">Bounding rectangle of the first sprite</param>
/// <param name="dataA">Pixel data of the first sprite</param>
/// <param name="rectangleB">Bouding rectangle of the second sprite</param>
/// <param name="dataB">Pixel data of the second sprite</param>
/// <returns>True if non-transparent pixels overlap; false otherwise</returns>
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;
}
我找到了一些解释,但没有人解释最后一行:
// If both pixels are not completely transparent,
if (colorA.A != 0 && colorB.A != 0)
{
// then an intersection has been found
return true;
}
这个colorA.A
属性是什么?为什么这个if语句确定发生了碰撞?
答案 0 :(得分:4)
Color.A
属性是alpha-value of the color。 0
表示完全透明,255
表示完全不透明。
如果其中一种颜色在指定像素处完全透明,则不会发生碰撞(因为其中一个对象不在此处,而只在其边界框处)。
只有当它们都是!= 0
时,实际上在同一个地方才有两个对象,并且必须处理碰撞。
例如,请参阅此图片:
边界框(黑色矩形)相交,但你不会认为它是红色和黄色圆圈之间的碰撞。
因此,您必须检查交叉像素处的颜色。如果它们是透明的(在此示例中为白色),则圆圈本身不相交。
这就是为什么你必须检查对象的颜色是否透明。如果其中一个是透明的,则对象本身不与另一个对象相交,只与其边界框相交。