Ground Box doesn't work in LibGdx and Box2D with Scene2d

32 views Asked by At

I've read so much about "pixel meters", viewports, etc. I got it to some extent, I think. Have now created a scene2d to test. But something is wrong with the conversion of the ground box, I think. The banana flies to the ground (groud box) at normal speed. After contact with the ground, however, the banana is thrown away again (upwards). Gravity and everything else are set correctly. With another project without converting the P2M it works, but is very slow. It would be great if someone could explain EXACTLY (possibly with code) how best to use box2D with scene2d. I just can't get any further. The explanations on the net are always difficult to implement.

P2M.PPM=100; 1 Meter = 100 Pixel (Would then see Viewport Box2d size widht 10, height 8)

enter image description here

 public BaseScreen()
{



    assMan.loadAll();
    assMan.manager.finishLoading();

    mainStage = new Stage(viewport=new ExtendViewport(1000,800));
    uiStage = new Stage(viewport=new ExtendViewport(1000,800));

Resize in BaseScreen:

 // methods required by Screen interface
public void resize(int width, int height) {
    
    viewport.update(width, height);
}

LevelScreen:

 public void initialize()
{

    batch = new SpriteBatch();

    TextureAtlas atlas;
    atlas = new TextureAtlas(Gdx.files.internal("sprites.txt"));
    TextureAtlas.AtlasRegion region = atlas.findRegion("banana");
    bananas = atlas.createSprite("banana");
    test = atlas.createSprite("banana");


    //        camera1 = new OrthographicCamera();
    //        viewport1 = new ExtendViewport(10, 8, camera1);


    Box2D.init();
    world = new World(new Vector2(0, -20), true);
    physicsBodies = new PhysicsShapeCache("physics.xml");

    debugRenderer = new Box2DDebugRenderer();

    createGround();
    generateFruit();
    createCollisionListener();



    /* BaseActor space = new BaseActor(0,0, mainStage);
    space.loadTexture("badlogic.jpg");

    space.setSize(1000,800);
    BaseActor.setWorldBounds(space);*/


}

 private void generateFruit() {

    float width = bananas.getWidth() * SCALE;
    float height = bananas.getHeight() * SCALE;

    bananas.setSize(width, height);
    bananas.setOrigin(0, 0);

    name="banana";
    frucht=createBody(name,200 / P2M.PPM,800 /P2M.PPM,0);


}

private Body createBody(String name, float x, float y, float rotation) {
    Body body = physicsBodies.createBody(name, world, SCALE, SCALE);
    body.setUserData("BANANE");
    body.setTransform(x, y, rotation);

    return body;
}

private void drawSprite(String name1, float x, float y, float degrees) {

    Sprite sprite = bananas;//sprites.get(name);
    sprite.setPosition(x, y);
    sprite.setRotation(degrees);
    sprite.draw(batch);
}

private void createGround() {
    if (ground != null) world.destroyBody(ground);

    BodyDef bodyDef = new BodyDef();
    bodyDef.type = BodyDef.BodyType.StaticBody;


    FixtureDef fixtureDef = new FixtureDef();
    fixtureDef.friction = 1;
    PolygonShape shape = new PolygonShape();
    shape.setAsBox(1000   , 0.9f );//0.5f 1000 / P2M.PPM +20

    fixtureDef.shape = shape;

    ground = world.createBody(bodyDef);
    ground.createFixture(fixtureDef);
    ground.setTransform(0 , 0 , 0);
    ground.setUserData("BODEN");




    shape.dispose();
}


 public void update(float dt)
{
    stepWorld();

    int numContacts = world.getContactCount();
    if (numContacts > 0) {
        Gdx.app.log("contact", "start of contact list");
        for (Contact contact : world.getContactList()) {
            Fixture fixtureA = contact.getFixtureA();
            Fixture fixtureB = contact.getFixtureB();

            /*Gdx.app.log("contact", "between " + fixtureA.getBody().getUserData()
                    + " and " + fixtureB.getBody().getUserData());*/

            String a= fixtureA.getBody().getUserData().toString();
            String b= fixtureB.getBody().getUserData().toString();

            Gdx.app.log("contact", "between " + a
                    + " and " + b);

            //Kollidiert Banane mit Boden?******************************************************
            if(a.equals("BANANE") && b.equals("BODEN")){

                Gdx.app.log("TEST", "TEST ERFOLGREICH");
            }

            //Alles andere Auswerten...

            //**********************************************************************************

            //Mit statischen body kollidiert?***************************************************
            if(fixtureA.getBody().getType() == BodyDef.BodyType.StaticBody){
                Gdx.app.log("Contact", "A=STATISCH");

            }
            if(fixtureB.getBody().getType() == BodyDef.BodyType.StaticBody){
                Gdx.app.log("Contact", "B=STATISCH");
            }
            //**********************************************************************************
        }
        Gdx.app.log("contact", "end of contact list");

    }





    batch.begin();
    //        test.draw(batch);

    Body body = frucht;
    String name1 = "banana";

    Vector2 position = body.getPosition();
    float degrees = (float) Math.toDegrees(body.getAngle());
    drawSprite(name1, position.x * P2M.PPM, position.y * P2M.PPM, degrees);

    Vector2 position1 = ground.getPosition();



    batch.end();

    //        uncomment to show the polygons
    //         debugRenderer.render(world, camera1.combined);

}




private void stepWorld() {
    float delta = Gdx.graphics.getDeltaTime();
    accumulator += Math.min(delta, 0.25f);



    if (accumulator >= STEP_TIME) {
        accumulator -= STEP_TIME;
        world.step(STEP_TIME, VELOCITY_ITERATIONS, POSITION_ITERATIONS);
    }
}
1

There are 1 answers

0
Jiří On

It is normal that the objects bounce from one another. This can be controlled by setting restitution when creating the body by using FixtureDef. But I see you are using some way to load the data from file physics.xml, so I think you can control the restitution in the program using which you created this file. To disable the bouncing you will want to set the value to 0.