Search code examples
libgdxbox2dcollision-detectiongame-physics

Libgdx collision detection with Physics Body Editor


I have recently started developing with Libgdx. Now, I'm looking at collision detection for custom shapes. In my case, I want to detect the collision of a shark with other objects. As a shark is a custom shape, I used the Physics Body Editor (https://code.google.com/p/box2d-editor/downloads/detail?name=physics-body-editor-2.9.2.zip&can=2&q=) to transform the shape into a json format.

I already have the code for the image drawing of the sharks and other stuff, but now I have no clue of how to implement the detection of collission with the json file. The tutorial on the phycics body editor website uses a different approach than I do.

Right now, I am drawing my shark like this in my render method:

batcher.draw(sharkAnimation, shark.getX(),
                        shark.getY(), shark.getWidth(), shark.getHeight());

sharkAnimation is a TextureRegion, and shark is an object with an X, Y, width and height. The sharks width and height are variable, but maintain the same ratio's.

I already got the bodyeditor for libgdx, and I'm experimenting with the following code, but honestly I have no clue of how I should handle this.

BodyEditorLoader loader = new BodyEditorLoader(
                Gdx.files.internal("data/shark.json"));

        // 1. Create a BodyDef, as usual.
        BodyDef bd = new BodyDef();
        bd.position.set(0, 0);
        bd.type = BodyType.DynamicBody;

        // 2. Create a FixtureDef, as usual.
        FixtureDef fd = new FixtureDef();
        fd.density = 1;
        fd.friction = 0.5f;
        fd.restitution = 0.3f;
loader.attachFixture(????, ????, ???, ????);

Help is greatly apreciated.


Solution

  • You need to create a body, and then use the loader the attach the fixture you created in the editor to that body.

    Body body = getWorld().createBody(bd);
    loader.attachFixture(body, name, fd, scale);
    

    The name is whatever you called it in the physics editor. Scale is how much you want to scale it by from the default size. Just use 1 if you don't want to change it.