Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java/libGDX - how to check Polygon collision with Rectangle or Circle

I'm new to libGDX and from what I can tell the Intersector class has overlap methods for Rectangle/Rectangle, Circle/Circle, Circle/Rectangle, and Polygon/Polygon, but for some reason it doesn't seem to have any methods for checking Polygon/Rectangle or Polygon/Circle.

Is there a recommended way to check for collision between polygon and rect/circle?

Also, is there some reason why this has been left out of the Intersector class? (ie, should I avoid it? If so, what's the recommended alternative?)

like image 958
1337ingDisorder Avatar asked Feb 15 '15 01:02

1337ingDisorder


2 Answers

The solution I've used to implement these checks without Box2D is as follows..

Check for collisions between Polygon and Rectangle:

// Check if Polygon intersects Rectangle
private boolean isCollision(Polygon p, Rectangle r) {
    Polygon rPoly = new Polygon(new float[] { 0, 0, r.width, 0, r.width,
            r.height, 0, r.height });
    rPoly.setPosition(r.x, r.y);
    if (Intersector.overlapConvexPolygons(rPoly, p))
        return true;
    return false;
}

Check for collisions between Polygon and Circle:

// 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 Poly/Circle check illustrated here was written by Cristiano Santos in this thread and the Poly/Rect check is a quick homebrew solution I came up with.

like image 90
1337ingDisorder Avatar answered Nov 10 '22 17:11

1337ingDisorder


The best way to handle those collisions would be to use a physics engine like Box2D which already comes packed with Libgdx. When a collision occurs in Box2D a event gets fired and you can easly handle that event. So you should probably take a look here.

Of course there are other ways of dealing of dealing with collision detection. With a little bit of maths you could probaly figure out just what you need on your own, also Box2D comes with alot of other features that will benefit you.

like image 2
dHoja Avatar answered Nov 10 '22 18:11

dHoja