Search code examples
libgdxbox2d

How to make a rope in libGDX box2D more springy?


I created few Box2D rope joints in libGDX. The ropes feel a bit too floppy. How can you make the ropes more stiff? The main Box2D project shows an option for stiffness in their testbed demo: enter image description here The rope on the right side shows the desired stiffness: enter image description here

Does such option exist in libGDX Box2D?

Thats how I create my ropes in libGDX:

private void initRopeJoints() {
    Array<Body> bodies = new Array<Body>();
    bodies.add(BodyBuilder.createBox(world,250,360,32,32,true,true));
    for(int i = 1; i < 5; ++i) {
        bodies.add(BodyBuilder.createBox(world, 250, -i * 32 +300, 4, 32, false, false));
        RopeJointDef rDef = new RopeJointDef();
        rDef.bodyA = bodies.get(i - 1);
        rDef.bodyB = bodies.get(i);
        rDef.collideConnected = true;
        rDef.maxLength = 1f; // meters because box2d works in meters
        rDef.localAnchorA.set(0, -0.5f);
        rDef.localAnchorB.set(0, .5f);
        world.createJoint(rDef);
    }
}

// makes stronger rope - e.g. will not break
private void initRopeJointsSecondApproach() {
    Array<Body> bodies = new Array<Body>();
    bodies.add(BodyBuilder.createBox(world,250,60 +270,32,4,true,true));
    for(int i = 1; i < 20; ++i) {
        bodies.add(BodyBuilder.createBox(world, 250, -i * 4 +270, 4, 4, false, false));
        RopeJointDef rDef = new RopeJointDef();
        rDef.bodyA = bodies.get(0);
        rDef.bodyB = bodies.get(i);
        rDef.collideConnected = true;
        rDef.maxLength = i * .25f;
        rDef.localAnchorA.set(0, -.125f);
        rDef.localAnchorB.set(0, .125f);

        world.createJoint(rDef);

        RevoluteJointDef jDef = new RevoluteJointDef();
        jDef.bodyA = bodies.get(i - 1);
        jDef.bodyB = bodies.get(i);
        jDef.localAnchorA.set(0, -.125f);
        jDef.localAnchorB.set(0, .125f);

        world.createJoint(jDef);
    }
}

Solution

  • Oh, I get it. The joints (RopeJoint/RevoluteJoint) will not provide you with the desired effect, since they do not restrict the rotation of bodies around each other. Use WeldJoint with adjusted parameters frequency and damping ratio.

    setDampingRatio(float ratio); setFrequency(float hz);

    It is difficult to say which parameters of frequency and damping ratio you need. Change them until the flexibility you need is achieved.