Collision Detection for 2D

Posted by Bhaskar on Game Development See other posts from Game Development or by Bhaskar
Published on 2011-01-01T12:15:57Z Indexed on 2011/01/01 12:58 UTC
Read the original article Hit count: 339

Filed under:

I am working on a simple game, where I need to do a collision detection of two Texture2D. The code I have written is:

bool perPixelCollission = false;
            Texture2D texture1 = sprite1.Texture;
            Texture2D texture2 = sprite1.Texture;
            Vector2 position1 = new Vector2(sprite1.CurrentScope.X, sprite1.CurrentScope.Y);
            Vector2 position2 = new Vector2(sprite2.CurrentScope.X, sprite2.CurrentScope.Y);

            uint[] bitsA = new uint[texture1.Width * texture1.Height];
            uint[] bitsB = new uint[texture2.Width * texture2.Height];

            Rectangle texture1Rectangle = new Rectangle(Convert.ToInt32(position1.X), Convert.ToInt32(position1.Y), texture1.Width, texture1.Height);
            Rectangle texture2Rectangle = new Rectangle(Convert.ToInt32(position2.X), Convert.ToInt32(position2.Y), texture2.Width, texture2.Height);

            texture1.GetData<uint>(bitsA);
            texture2.GetData<uint>(bitsB);

            int x1 = Math.Max(texture1Rectangle.X, texture2Rectangle.X);
            int x2 = Math.Min(texture1Rectangle.X + texture1Rectangle.Width, texture2Rectangle.X + texture2Rectangle.Width);

            int y1 = Math.Max(texture1Rectangle.Y, texture2Rectangle.Y);
            int y2 = Math.Min(texture1Rectangle.Y + texture1Rectangle.Height, texture2Rectangle.Y + texture2Rectangle.Height);

            for (int y = y1; y < y2; ++y)
            {
                for (int x = x1; x < x2; ++x)
                {
                    if (((bitsA[(x - texture1Rectangle.X) + (y - texture1Rectangle.Y) * texture1Rectangle.Width] & 0xFF000000) >> 24) > 20 &&
                        ((bitsB[(x - texture2Rectangle.X) + (y - texture2Rectangle.Y) * texture2Rectangle.Width] & 0xFF000000) >> 24) > 20)
                    {
                        perPixelCollission = true;
                        break;
                    }
                }
                // Reduce amount of looping by breaking out of this.
                if (perPixelCollission)
                {
                    break;
                }
            }

            return perPixelCollission;

But this code is really making the game slow. Where can I get some very good collision detection tutorial and code? What is wrong in this code?

© Game Development or respective owner

Related posts about games-for-windows