What's the best way to do collision detection?

2019-08-07 06:08发布

问题:

I have a need to define a polygon that would be the "legal" area, and allow a user to move a rectangle around within that polygon, preventing them from moving the rectangle anywhere where its points venture outside the polygon.

The polygon is a fixed shape, so, I was thinking it may be easiest to import a PNG of that shape and pull the points in that way, somehow? But I'm still at a loss as to the math involved in checking the coordinates of the rectangle as the user drags it, and testing at what point they have moved the shape to the edge of the bounding polygon.

Unfortunately the bounding polygon is a fairly complex shape. I'm hoping someone can point me at a tutorial that shows what the best way to run such a collision detection is.

回答1:

Metanet's excellent collision detection tutorial has a good section on how to do swept collision with axis-aligned bounding boxes (AABB) and arbitrary "walls."

If your polygon is concave, you'll probably find it easiest to first decompose it into multiple convex polygons, which will simplify the available collision detection algorithms.



回答2:

If you only looking to check the corners of the rectangle, you can do a "inside" test for each of them. http://en.wikipedia.org/wiki/Point_in_polygon

And if you also want to make sure that no pointy part of the polygon "punctures" your rectangle you could do a test for each of the 4 lines in the rectangle against all the lines in the polygon to see if they are intersecting. http://en.wikipedia.org/wiki/Line-line_intersection