【问题标题】:XNA Getting colour data from a spritesheet is crashing the gameXNA 从 spritesheet 获取颜色数据会使游戏崩溃
【发布时间】:2012-12-09 23:31:51
【问题描述】:

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

我做错了什么?

【问题讨论】:

    标签: c# xna collision


    【解决方案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)是否等于任何值。

    【讨论】:

    • 非常感谢!我会 +1 你的回答,但我是新来的,所以
    猜你喜欢
    • 2012-07-27
    • 2011-07-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多