【问题标题】:Per-Pixel collision code每像素碰撞代码
【发布时间】:2013-12-16 09:34:14
【问题描述】:

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

/// <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 语句确定发生了冲突?

【问题讨论】:

  • 如果两个像素都不透明,那么两个像素正在碰撞。即忽略透明像素。 'A' 是 alpha 值

标签: c# xna


【解决方案1】:

Color.A 属性是alpha-value of the color0 表示完全透明,255 表示完全不透明。

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

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

例如看这张图片:

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

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

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

【讨论】:

  • 很抱歉,但我不明白透明度与碰撞检查有什么关系。也许我不理解整个代码,而不是这些行。
  • 非常感谢,我现在终于明白了。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-11-12
  • 1970-01-01
相关资源
最近更新 更多