Follow me on Twitter RSS FEED

XNA Game Studio: Complex Polygon Collisions

I am working on an NHL shootout game in XNA Game Studio. I had the basic prototype down, with player movement, shooting and grabbing the puck, and a goal. The only thing left was to detect when the puck should bounce off the posts of the goal, and when the puck goes into the goal. I could have just used multiple Rectangle objects, but I decided to figure out how to do Polygon Collision Checking. It would be good to know how to do it, for future reference.

Some Google searches revealed this link. I copied and pasted the function, and made some tweaks. I put it in a Polygon class, which stores a generic List<> of Vector2s. Then I added a funtion:

public bool Intersects(Polygon other)
        {
            foreach (Vector2 point in other.points)
            {
                if(PointInPolygon(point))
                    return true;
            }
            return false;
        }

Then all I had to do was create the polygon collision bounds for all the objects, and say something like:

if (puckBounds.Intersects(goalBounds))
        {
            // Make puck bounce here
        }

I'm glad I learned this, because I'll be able to use my Polygon class for lots of things in the future. Maybe later I can upload the source and/or upload a compiled DLL.

2 comments:

Anonymous said...

Your intersection test is incomplete. Consider the case of two rectangles that overlap to form a cross. Neither one contains a vertex of the other.

Adam Gaskins said...

Oh, heh, nice catch! I would never have caught that, given what I was using it for. I can't think of any quick solutions at the moment... maybe I'll do a followup post...

Post a Comment