Search code examples
javaandroidandroid-studiolibgdxbox2d

Box2D Android Studio Drawing inverted shapes


I'm creating a crash test game using Android Studio and LibGDX, I have everything I need on the game set, however I would like to create an upside down triangle like this in Box2D, Obviously, It's not going to look like this but this image is to give you an exampleExample of my goal on Box2D

However when I run it it looks like this: Actual result

I've tried changing the order of the code in Box2D but it doesn't create an inverted triangle, like this :

private Fixture createcollisionFixture(Body collisionBody) {
        Vector2[] vertices = new Vector2[3];
        vertices[0] = new Vector2(-0.5f, -0.5f);
        vertices[1] = new Vector2(0.5f, -0.5f);
        vertices[2] = new Vector2(0, 0.5f);
        PolygonShape shape = new PolygonShape();
        shape.set(vertices);
        Fixture fix = collisionBodyBody.createFixture(shape, 1);
        shape.dispose();
        return fix;
    }

I change it to:

private Fixture createcollision2Fixture(Body collision2Body) {
        Vector2[] vertices = new Vector2[3];
        vertices[2] = new Vector2(0, 0.5f);
        vertices[1] = new Vector2(0.5f, -0.5f);
        vertices[0] = new Vector2(-0.5f, -0.5f);
        PolygonShape shape = new PolygonShape();
        shape.set(vertices);
        Fixture fix = collision2Body.createFixture(shape, 1);
        shape.dispose();
        return fix;

    }

But it keeps loading as the second picture, not like an inverted triangle, how do I fix this? Help would be greatly appreciated.


Solution

  • The problem is not in Box2D but in coordinates that you are using to draw triangle. No matter in what order you will be passing them to the Fixture they will produce triangle like this:

    enter image description here

    If you want to rotate the triangle you have to pass another set of coordinates like this:

    enter image description here

    So finally your code should look like:

        ...
    
        Vector2[] vertices = new Vector2[3];
        vertices[2] = new Vector2(-0.5, 0.5f);
        vertices[1] = new Vector2(0.5f, 0.5f);
        vertices[0] = new Vector2(0.5f, -0.5f);
    
        ...