Take the 2-minute tour ×
Game Development Stack Exchange is a question and answer site for professional and independent game developers. It's 100% free, no registration required.

Is there a well-known way (or perhaps reusable bit of code) for pixel-perfect collision detection in XNA?

I assume this would also use polygons (boxes/triangles/circles) for a first-pass, quick-test for collisions, and if that test indicated a collision, it would then search for a per-pixel collision.

This can be complicated, because we have to account for scale, rotation, and transparency.

WARNING: If you're using the sample code from the link from the answer below, be aware that the scaling of the matrix is commented out for good reason. You don't need to uncomment it out to get scaling to work.

share|improve this question
Polygons or sprites? –  Jonathan Hobbs Jul 25 '11 at 14:38
I'm not sure. Xna supports both? My edit mentions a combination of both, since bounding-box tests are a fast first-pass. –  ashes999 Jul 26 '11 at 3:31
The collision detection will differ depending on whether you are using 3D/2D models or sprites. One has pixels. The other has vertices and edges. –  Jonathan Hobbs Jul 26 '11 at 11:17
Okay, I see what you're getting at now. I'm using sprites. Although I believe XNA implements them as a textured polygons. –  ashes999 Jul 26 '11 at 11:22
add comment

2 Answers

up vote 21 down vote accepted

I see that you tagged the question as 2d, so I'll go ahead and dump my code:

class Sprite {


    public bool CollidesWith(Sprite other)
        // Default behavior uses per-pixel collision detection
        return CollidesWith(other, true);

    public bool CollidesWith(Sprite other, bool calcPerPixel)
        // Get dimensions of texture
        int widthOther = other.Texture.Width;
        int heightOther = other.Texture.Height;
        int widthMe = Texture.Width;
        int heightMe = Texture.Height;

        if ( calcPerPixel &&                                // if we need per pixel
            (( Math.Min(widthOther, heightOther) > 100) ||  // at least avoid doing it
            ( Math.Min(widthMe, heightMe) > 100)))          // for small sizes (nobody will notice :P)
            return Bounds.Intersects(other.Bounds) // If simple intersection fails, don't even bother with per-pixel
                && PerPixelCollision(this, other);

        return Bounds.Intersects(other.Bounds);

    static bool PerPixelCollision(Sprite a, Sprite b)
        // Get Color data of each Texture
        Color[] bitsA = new Color[a.Texture.Width * a.Texture.Height];
        Color[] bitsB = new Color[b.Texture.Width * b.Texture.Height];

        // Calculate the intersecting rectangle
        int x1 = Math.Max(a.Bounds.X, b.Bounds.X);
        int x2 = Math.Min(a.Bounds.X + a.Bounds.Width, b.Bounds.X + b.Bounds.Width);

        int y1 = Math.Max(a.Bounds.Y, b.Bounds.Y);
        int y2 = Math.Min(a.Bounds.Y + a.Bounds.Height, b.Bounds.Y + b.Bounds.Height);

         // For each single pixel in the intersecting rectangle
         for (int y = y1; y < y2; ++y)
             for (int x = x1; x < x2; ++x)
                 // Get the color from each texture
                 Color a = bitsA[(x - a.Bounds.X) + (y - a.Bounds.Y)*a.Texture.Width];
                 Color b = bitsB[(x - b.Bounds.X) + (y - b.Bounds.Y)*b.Texture.Width];

                 if (a.A != 0 && b.A != 0) // If both colors are not transparent (the alpha channel is not 0), then there is a collision
                     return true;
        // If no collision occurred by now, we're clear.
        return false;

    private Rectangle bounds = Rectangle.Empty;
    public virtual Rectangle Bounds
            return new Rectangle(
                (int)Position.X - Texture.Width,
                (int)Position.Y - Texture.Height,


Edit: While this code is almost self explanatory, I did feel bad for not having comments, so I added some ;) I also got rid of the bitwise operations since it was doing basically what the Color.A property does in a more complicated way ;)

share|improve this answer
Down-vote for a code dump with no comments or explanation. –  AttackingHobo Jul 25 '11 at 19:31
Any explanation would just be restating the code, and the code is fairly straightforward. –  user744 Jul 25 '11 at 19:45
The code tells you what. Any comments tell you why. However, this code is fairly straightforward to not need the why. –  Neeko Jul 25 '11 at 19:47
I know I mentioned this in my question, but I need to state it again: does this handle scaling and rotation? Can two scaled, rotated sprites correctly intersect? (I can handle adding a quick bounding-box first pass though.) Or is this covered with calls to Bounds? –  ashes999 Jul 26 '11 at 3:33
Just being pedantic, but you only need : CollidesWith(Sprite other, bool calcPerPixel = true); :) –  Jonathan Connell Aug 8 '11 at 21:16
show 3 more comments

On the App Hub, there is a very old sample that walks you through 2D collision detection from simple bounding boxes to pixel-tested on rotated and scaled sprites. It has been fully updated to 4.0. The whole series is worth a read if you are new to the topic.


I also found Riemer Grootjans approach interesting in his 2D shooters game. http://www.riemers.net/eng/Tutorials/XNA/Csharp/series2d.php

(It takes him a little while to get to it... http://www.riemers.net/eng/Tutorials/XNA/Csharp/Series2D/Coll_Detection_Overview.php ... but you may want to follow along to see the problem he is solving)

But I caution you that Riemers sample is not XNA 4.0 and you may have to do a little work to get it running. It's not difficult or mysterious work, however.

share|improve this answer
Great links, but old links; I've used these already for my solution. –  ashes999 Sep 28 '11 at 14:02
Awesome. I just figure when someone searches they can find your question and they'll have more resources. –  Chris Gomez Sep 30 '11 at 14:46
add comment

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.