tags:

views:

300

answers:

2

In my XNA game, I needed to define an irregular shape based on several Vector2 coordinates in the 2D space. The reason was to do collision check (like Rectangle.Intersects()).

For example:

Vector2 point1 = new Vector(20,30);
Vector2 point2 = new Vector(60,30);
Vector2 point3 = new Vector(60,80);
Vector2 point4 = new Vector(40,90);
Vector2 point5 = new Vector(20,80);

would create a shape that has paths that goes from point1 -> point2 -> point3 -> point4 -> point5 then back to point1.

However I couldn't find a proper solution to implement this. Please help. Thanks.

A: 

ZiggyWare (formerly www.ziggyware.com) have a tutorial on 2D polygon collision detection but it seems that ZW is in the process of moving to a new home. Here's a video though, of how the tutorial looks like.

Peter Lillevold
+1  A: 

There are a couple of different approaches to what you want to do. You mentioned collision detection: do you want to determine if a point intersects the shape, or do you want to determine if two polygons intersect?

If you want a point, what you're looking for is called a "point in polygon test". There are a number of different approaches, but one of the quickest and most straight forward approaches is a ray test. You create a ray from your point and count the number of times it crosses the edges. If the number is even, the point is outside. If it's odd, the point is inside.

You can find a good article on this here: http://www.ecse.rpi.edu/Homepages/wrf/Research/Short_Notes/pnpoly.html

The code implementation from the article looks like so:

int pnpoly(int nvert, float *vertx, float *verty, float testx, float testy)
{
  int i, j, c = 0;
  for (i = 0, j = nvert-1; i < nvert; j = i++) {
    if ( ((verty[i]>testy) != (verty[j]>testy)) &&
     (testx < (vertx[j]-vertx[i]) * (testy-verty[i]) / (verty[j]-verty[i]) + vertx[i]) )
       c = !c;
  }
  return c;
}

Determining if two polygons intersect is more complicated, but not entirely dissimilar. A lot of games actually just check the corners of the polygons with point-in-poly as its easy and cheap, but it is possible to check the complete intersection as well.

One way you can approach it is to treat each edge as a dividing plane / halfspace. The intersection of the halfspaces determines if the two polygons intersect.

Try searching for "Separating Axis Theorem".