Box2D WeldJoint无法正常工作

时间:2017-01-09 12:19:33

标签: java libgdx box2d box2d-joints

在我的问题面前,我的英语非常冒险......

在我的libgdx应用程序中,我实现了Box2D。所以我创建了一个世界并添加了2个Bodys。第一个Body是一个PolygonShape,设置为盒子,它是静态的,在我的世界中间旋转。第二个身体只是一个圆圈,它是动态的,落在第一个身体的顶部。当坠落的圆圈与Box碰撞时,我创建了一个WeldJoint,并期望圆圈现在也随着盒子旋转...... 但是在大约20度之后,圆圈停止了他在盒子内的旋转而不再移动......

这是一张图片: works correctly like glue

另一个: stops his rotation around the box

我的代码:

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!");
            }
        }

在我的渲染循环中:

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");
    }

忽略不良代码,仅用于测试......

谢谢:)

0 个答案:

没有答案