PABLO FERNANDEZ
PABLO FERNANDEZ

Reputation: 5

Collision Polygon and Circle - Lingdx

I want to detect when a polygon and a Circle collide. Other possibility that i have think is with rectangle, but it can't be possible because i want to rotate the rectangle, so what is the solution?

Thank you

Upvotes: 0

Views: 173

Answers (1)

Mobador
Mobador

Reputation: 101

There is Intersector class in LibGDX, it should work just fine for your needs. libgdx.badlogicgames.com/nightlies/docs/api/com/badlogic/gdx/math/Intersector.html

Use intersectSegmentCircle method. It does take Vector2 variables as arguments, so you have to use Vector2 for storing x and y coordinates of your points - circle center and polygon vertices. There are also Polygon and Circle classes, you can use those for storing coordinates as Vector2.

Anyway, lets assume you already have circle and polygon described by set of Vector2 points:

Vector2 circleCenter, PolyVertex1, PolyVertex2, PolyVertex3, ..., PolyVertexN;

There are line segments between polygon vertices, you have to check, if any of those segments intersects with circle. So, for every pair of verices, check, if:

intersectSegmentCircle(PolyVertex1, PolyVertex2, circleCenter, radius^2);
intersectSegmentCircle(PolyVertex2, PolyVertex3, circleCenter, radius^2);
...
intersectSegmentCircle(PolyVertexN-1, PolyVertexN, circleCenter, radius^2);
intersectSegmentCircle(PolyVertexN, PolyVertex1), circleCenter, radius^2);

returns true. If yes, it means your polygon and circle colided.

In some cases (small circle and large polygon), there can be no intersection between polygon edges and circle, whole circle can be inside polygon. Then you will have to use isPointInPolygon() method. It takes Array of Vector2 (polygon vertices) and Vector2 (cirlce center) as arguments. So, store polygon vertices in array, and check if isPointInPolygon returns true. If yes, then again, there is collision.

Array <Vector2> PolyVertices;
...
isPointInPolygon(PolyVertices,circleCenter);

Dont copy&paste above code, wont work because of lack of initialization and thelike ;) But i hope, idea is clear.

Upvotes: 2

Related Questions