I'm trying to make a little game for Android with LibGDX and am having a hard time with collision detection. So, I have two shapes : The first one is a rectangle (the player) :
shapeRenderer.begin(ShapeRenderer.ShapeType.Filled);
shapeRenderer.setColor(Color.BLACK);
shapeRenderer.rect(position.x, position.y, width, height);
shapeRenderer.end();
The second one is the following, kind of a cage :
shapeRenderer.begin(ShapeRenderer.ShapeType.Filled);
shapeRenderer.setColor(Color.BLACK);
shapeRenderer.rect(0, 0, 50, Gdx.graphics.getHeight());
shapeRenderer.rect(0, 0, Gdx.graphics.getWidth(), 50);
shapeRenderer.rect(Gdx.graphics.getWidth()-50, 0, 50, Gdx.graphics.getHeight());
shapeRenderer.rect(0, Gdx.graphics.getHeight()-50, Gdx.graphics.getWidth(), 50);
shapeRenderer.end();
My question is :
How can I detect collision between these two objects ? The only way I know, how to detect collision is with the intersect method from the Rectangle class but I would like to make more complex shapes than rectangles.
Thank you for your help !
According to documentation ShapeRenderer
isn't efficient and shouldn't be used intensively.
Renders points, lines, rectangles, filled rectangles and boxes. This class is not meant to be used for performance sensitive applications but more oriented towards debugging.
A better approach might be to allocate a Sprite
with a small white texture that you upscale to the appropriate size. Set tint and alpha with setColor(..) method.
For collision getBoundingRectangle()
of Sprite return bounding axis aligned Rectangle, that will help you in collision.
You can manually create a texture by using pixmap.
public static Texture createBgTexture() {
Pixmap pixmap = new Pixmap(1, 1, Format.RGBA8888);
pixmap.setColor(Color.WHITE);
pixmap.fill();
Texture texture = new Texture(pixmap); // must be manually disposed
pixmap.dispose();
return texture;
}
For more complex shape use Physics Body Editor, that will return vertex point of your shape in readable file format, use that points and create Polygon.
Libgdx having Intersector
class, containing many static method for collision detection like intersectPolygons(....)
and more.
On the other hand If you want a realistic collision detection, You can use box2d in your game. Inside box2d API there is a ContactListener
interface that will tell you when two body collide.