Reputation: 1
I've recently found code on stackoverflow, that is used to handle collision beteween polygon and circle and it works. The problem is beacause I do not quite understand it so I would be greatful if somebody could provide me simple explanation.
// Check if Polygon intersects Circle
private boolean isCollision(Polygon p, Circle c) {
float[] vertices = p.getTransformedVertices();
Vector2 center = new Vector2(c.x, c.y);
float squareRadius = c.radius * c.radius;
for (int i = 0; i < vertices.length; i += 2) {
if (i == 0) {
if (Intersector.intersectSegmentCircle(new Vector2(
vertices[vertices.length - 2],
vertices[vertices.length - 1]), new Vector2(
vertices[i], vertices[i + 1]), center, squareRadius))
return true;
} else {
if (Intersector.intersectSegmentCircle(new Vector2(
vertices[i - 2], vertices[i - 1]), new Vector2(
vertices[i], vertices[i + 1]), center, squareRadius))
return true;
}
}
return false;
}
The part that I do not get it is the for loop.
Upvotes: 0
Views: 348
Reputation: 2163
intersectSegmentCircle
effectively takes a line segment (as specified by the first two vector arguments), and a circle (as specified by the last vector and float arguments), and returns true if the line intersects the circle.
The for loop is looping through the vertices of the polygon (incrementing by two since a vertex is represented by two values in float[] vertices
). For each vertex in turn, it considers the line segment formed by joining that vertex to the previous one in the polygon (i.e. it considers each edge of the polygon in turn).
If intersectSegmentCircle
finds a circle intersection for that segment, the method returns true. If no intersections are found by the end it returns false.
The if/else in the for loop is just for the first vertex - the 'previous' vertex in this case will actually be the last one in float[] vertices
, since a polygon loops round and joins the last vertex back to the first.
Upvotes: 1