0

ゲーム内の 2 つのオブジェクト間の衝突をピクセルごとにチェックするコードを理解しようとしました。コードは次のとおりです。

/// <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 ステートメントが衝突が発生したと判断するのはなぜですか?

4

1 に答える 1

4

Color.Aプロパティは color のアルファ値です0は完全に透明、255完全に不透明を意味します。

色の 1 つが指定されたピクセルで完全に透明な場合、衝突は発生しません (オブジェクトの 1 つがこの場所ではなく、そのバウンディング ボックスのみにあるため)。

両方が の場合のみ、!= 0実際には同じ場所に 2 つのオブジェクトがあり、衝突を処理する必要があります。

たとえば、次の画像を参照してください。bb交差点

境界ボックス (黒い四角形) は交差しますが、赤と黄色の円の間の衝突とは見なされません。

したがって、交差するピクセルで色を確認する必要があります。それらが透明な場合 (この例では白)、円自体は交差していません。

これが、オブジェクトの色が透明かどうかを確認する必要がある理由です。それらの 1 つが透明である場合、オブジェクト自体は他のオブジェクトと交差しておらず、境界ボックスだけが交差しています。

于 2013-05-30T09:41:39.607 に答える