2

我正在使用 C# 在 XNA 中构建一个小型自上而下的射击游戏,并且我正在尝试实现每像素碰撞检测。我有以下代码来执行此操作,以及返回包含碰撞的矩形的标准边界框检测。

private bool perPixel(Rectangle object1, Color[] dataA, Rectangle object2, Color[] dataB)
    {
        //Bounds of collision
        int top = Math.Max(object1.Top, object2.Top);
        int bottom = Math.Min(object1.Bottom, object2.Bottom);
        int left = Math.Max(object1.Left, object2.Left);
        int right = Math.Min(object1.Right, object2.Right);

        //Check every pixel
        for (int y = top; y < bottom; y++)
        {
            for (int x = left; x < right; x++)
            {
                //Check alpha values
                Color colourA = dataA[(x - object1.Left) + (y - object1.Top) * object1.Width];
                Color colourB = dataB[(x - object2.Left) + (y - object2.Top) * object2.Width];

                if (colourA.A != 0 && colourB.A != 0)
                {
                    return true;
                }
            }
        }
        return false;
    }

我很确定这会起作用,但我也试图从精灵表中获取一些要检查的对象,并且我正在尝试使用此代码来获取颜色数据,但它得到了一个错误说“传入的数据大小对于这个资源来说太大或太小”。

 Color[] pacmanColour = new Color[frameSize.X * frameSize.Y];

                pacman.GetData(0, new Rectangle(currentFrame.X * frameSize.X, currentFrame.Y * frameSize.Y, frameSize.X, frameSize.Y), pacmanColour,
                    currentFrame.X * currentFrame.Y, (sheetSize.X * sheetSize.Y));

我究竟做错了什么?

4

1 回答 1

1

让我向您展示我处理 Texture2D 颜色的方法

我使用以下技术从文件加载预制结构

//Load the texture from the content pipeline
Texture2D texture = Content.Load<Texture2D>("Your Texture Name and Directory");

//Convert the 1D array, to a 2D array for accessing data easily (Much easier to do Colors[x,y] than Colors[i],because it specifies an easy to read pixel)
Color[,] Colors = TextureTo2DArray(texture);

而且功能...

 Color[,] TextureTo2DArray(Texture2D texture)
    {
        Color[] colors1D = new Color[texture.Width * texture.Height]; //The hard to read,1D array
        texture.GetData(colors1D); //Get the colors and add them to the array

        Color[,] colors2D = new Color[texture.Width, texture.Height]; //The new, easy to read 2D array
        for (int x = 0; x < texture.Width; x++) //Convert!
            for (int y = 0; y < texture.Height; y++)
                colors2D[x, y] = colors1D[x + y * texture.Width];

        return colors2D; //Done!
    }

它将返回一个简单易用的二维颜色数组,因此您可以简单地检查 Colors[1,1](对于像素 1,1)是否等于任何值。

于 2012-12-22T20:57:47.877 回答