列表中的每像素冲突

时间:2018-05-27 20:54:16

标签: c# xna 2d collision-detection

标题说明了一切。我试图通过我为所有敌人工作的每像素碰撞方法进行碰撞。如果我不使用列表,我的方法可以正常工作。这是我使用的代码:

public bool IntersectPixels(
Matrix transformA, int widthA, int heightA, Color[] dataA,
Matrix transformB, int widthB, int heightB, Color[] dataB)
    {
        // Calculate a matrix which transforms from A's local space into
        // world space and then into B's local space
        Matrix transformAToB = transformA * Matrix.Invert(transformB);

        // For each row of pixels in A
        for (int yA = 0; yA < heightA; yA++)
        {
            // For each pixel in this row
            for (int xA = 0; xA < widthA; xA++)
            {
                // Calculate this pixel's location in B
                Vector2 positionInB =
                    Vector2.Transform(new Vector2(xA, yA), transformAToB);

                // Round to the nearest pixel
                int xB = (int)Math.Round(positionInB.X);
                int yB = (int)Math.Round(positionInB.Y);

                // If the pixel lies within the bounds of B
                if (0 <= xB && xB < widthB &&
                    0 <= yB && yB < heightB)
                {
                    // Get the colors of the overlapping pixels
                    Color colorA = dataA[xA + yA * widthA];
                    Color colorB = dataB[xB + yB * widthB];

                    // 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;
    }

要检查冲突,我使用这段代码:

public bool Update(Matrix PersonTransform2,Color[] data2)
    {
        personTransform1 = Matrix.CreateTranslation(new Vector3(new Vector2(position.X, position.Y), 0.0f));
        if (game.IntersectPixels(PersonTransform2, texture.Width, texture.Height, data2,
            PersonTransform1, texture.Width, texture.Height, data1))
        {
            return true;
        }
        return false;
    }

我的问题是如何将这段代码转换为能够使用列表。

2 个答案:

答案 0 :(得分:0)

您可以添加一个重载并使用Linq中的ToArray():

public bool Update(Matrix personTransform2, List<Color> data2)
{
    Update(Matrix personTransform2, data2.ToArray())
}

但是由于性能(上面创建了一个副本),我可能会在两个签名中用Color[]替换List<Color>

另一方面,对于这类计算,您可能不应该使用List<Color>开始。如果你直接关心数组的性能工作。

答案 1 :(得分:0)

犯了错误......我忘了把一个foreach循环遍历我的所有列表......代码是:

for(int i = 0; i < lista.Count; i++)
        {
            if (lista[i].Update(blockTransform, data2))
            {
                touched = true;
            }
        }
相关问题