Search code examples
androidcollision-detectionpolygonandroid-canvas

What's the best way to do collision detection?


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.


Solution

  • 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.