每像素冲突代码

我试图理解检查游戏中两个对象之间碰撞的代码 – 每像素碰撞。 代码是:

///  /// Determines if there is overlap of the non-transparent pixels /// between two sprites. ///  /// Bounding rectangle of the first sprite /// Pixel data of the first sprite /// Bouding rectangle of the second sprite /// Pixel data of the second sprite /// True if non-transparent pixels overlap; false otherwise 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语句确定发生了碰撞?

Color.A属性是颜色的alpha值 。 0表示完全透明, 255表示完全不透明。

如果其中一种颜色在指定像素处完全透明,则不会发生碰撞(因为其中一个对象不在此处,而只在其边界框处)。

只有当它们都是!= 0 ,实际上在同一个地方有两个对象并且必须处理碰撞。

请参阅此图片: bb十字路口

边界框(黑色矩形)相交,但您不会认为它是红色和黄色圆圈之间的碰撞。

因此,您必须检查交叉像素的颜色。 如果它们是透明的(在此示例中为白色),则圆圈本身不相交。

这就是为什么你必须检查对象的颜色是否透明。 如果其中一个是透明的,则对象本身不与另一个对象相交,只与其边界框相交。