XNA从spritesheet获取颜色数据正在使游戏崩溃

时间:2012-12-22 20:07:32

标签: c# xna collision

我正在使用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));

我做错了什么?

1 个答案:

答案 0 :(得分: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!
    }

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