Texture2D.GetData fails to return pixel colour data

Posted by Chris Charabaruk on Game Development See other posts from Game Development or by Chris Charabaruk
Published on 2011-01-06T04:40:40Z Indexed on 2011/01/06 5:00 UTC
Read the original article Hit count: 293

Filed under:
|
|

Because I'm using sprite sheets instead of an individual texture per sprite, I need to pass in a Rectangle when calling Texture2D.GetData() in my collision detection for per-pixel tests. Unfortunately, without fail I get an ArgumentException percolated down from an internal method inside the Texture (not Texture2D) class.

My code for getting the texture data looks like this:

    public override Color[] GetPixelData()
    {
        Color[] data = new Color[(int)size.Product()];
        Rectangle rect = new Rectangle(hframe * (int)size.X, vframe * (int)size.Y, (int)size.X, (int)size.Y);

#if DEBUG
        if (sprite.Bounds.Contains(rect) && sprite.Format == SurfaceFormat.Color)
#endif
            sprite.GetData(0, rect, data, 0, 1);

        return data;
    }

Even with the check to ensure I'm grabbing a valid rectangle and that the texture format matches what I'm trying to get, I still get that exception, claiming "The size of the data passed in is too large or too small for this resource." Unfortunately, the debugger won't let me check the locals within the Texture.ValidateTotalSize() method where the exception originates.

Has anyone else had this problem and knows how to fix it? I'm relying on AABB testing only for now, but that doesn't really work for some of my game's entities due to odd shapes, rotation and scaling.

© Game Development or respective owner

Related posts about XNA

Related posts about textures