Box2D WeldJoint not working correctly

271 Views Asked by At

In front of my question, my english is very adventurous...

In my libgdx application, I have implemented Box2D. So I created a World and add them 2 Bodys. The first Body is a PolygonShape set as box which is static and rotate in the middle of my world. The second body is just a circle, which is dynamic and falling on top of the first body. When the falling Circle is collide with the Box, I create a WeldJoint and expect, that the circle is now rotate with the box too... But after approx 20 degrees, the circle is stop his rotation within the box and don't move any more...

Here is a picture: works correctly like glue

another one: stops his rotation around the box

My code:

BodyDef bodyDef = new BodyDef();
    bodyDef.type = BodyType.StaticBody;
    bodyDef.position.set(10, 8);

    mainBox = world.createBody(bodyDef);

    PolygonShape polygonShape = new PolygonShape();
    polygonShape.setAsBox(1, .5F);
    mainBox.createFixture(polygonShape, 1);

    FixtureDef fixtureDef = new FixtureDef();
    fixtureDef.shape = polygonShape;
    fixtureDef.density = .1F;
    fixtureDef.friction = .5F;
    fixtureDef.restitution = .2F;

    Fixture f = mainBox.createFixture(fixtureDef);
    f.setUserData("mainbox");
    mainBox.setUserData("mainbox");

    /* ------------------------------------------------------------------------------------------ */

    bodyDef = new BodyDef();
    bodyDef.type = BodyType.DynamicBody;
    bodyDef.position.set(10, 20);

    shootBall = world.createBody(bodyDef);
    shootBall.setUserData("shootball");

    CircleShape circleShape = new CircleShape();
    circleShape.setRadius(.2F);


    fixtureDef = new FixtureDef();
    fixtureDef.shape = circleShape;
    fixtureDef.density = .5F;
    fixtureDef.friction = .5F;
    fixtureDef.restitution = .3F;

    f = shootBall.createFixture(fixtureDef);
    f.setUserData("shootball");

    circleShape.dispose();

    world.setContactListener(new ContactListener(){

        @Override
        public void beginContact(Contact contact) {
            if(contact.getFixtureA().getBody().getUserData().equals("mainbox") && contact.getFixtureB().getBody().getUserData().equals("shootball")){
                contact.getFixtureA().getBody().setUserData("createjoint");
                System.out.println("contact!");
            }
        }

And in my render-loop:

if(mainBox.getUserData().equals("createjoint")){
        WeldJointDef jointDef = new WeldJointDef();
        jointDef.bodyA = mainBox;
        jointDef.bodyB = shootBall;
        jointDef.initialize(mainBox, shootBall, mainBox.getPosition());
        world.createJoint(jointDef);
        mainBox.setUserData("mainbox");
    }

Ignore bad code, its just for testing...

thanks :)

0

There are 0 best solutions below