I am developing a game when i using a rope, that i created in Box2d using circles and joints. Rope works as expected when i drag it with low force, and in other cases (when force is more big) it just stretch like a crazy and i don't know how to fix it and create more stable rope. I tried diferent types of joints( RopeJoint, RevoluteJoint, DistanceJoint, etc.), but it's useless. Here is my code:
public class RopeItem {
public Body body;
private com.badlogic.gdx.graphics.g2d.Sprite bodySprite;
float width, length;
public CircleShape shape;
public RopeItem(World world, float width, float height, BodyType bodyType, Vector2 position) {
super();
//init body
BodyDef bodyDef = new BodyDef();
bodyDef.type = bodyType;
bodyDef.position.set(position);
this.body = world.createBody(bodyDef);
//init shape
FixtureDef fixtureDef = new FixtureDef();
fixtureDef.density = 0.1f;
fixtureDef.friction = 0.4f;
fixtureDef.restitution = 0.2f;
shape = new CircleShape();
shape.setRadius(width / 2);
fixtureDef.shape = shape;
fixtureDef.filter.categoryBits = 0x0001;
fixtureDef.filter.maskBits = 0x0002;
this.body.createFixture(fixtureDef);
shape.dispose();
//create a body sprite
bodySprite = new com.badlogic.gdx.graphics.g2d.Sprite(new TextureRegion(new Texture("data/rope_circle.png")));
bodySprite.setSize(width, height);
bodySprite.setOrigin(width/2, height/2);
body.setUserData(bodySprite);
}
}
public void createRope(int length) {
RevoluteJoint[] joints = new RevoluteJoint[length - 1];
RopeJoint[] ropeJoints = new RopeJoint[length - 1];
float width = 0.23f, height = 0.23f;
for(int i=0; i<length; i++) {
ropeSegmenets.add(new RopeItem(world, width, height, BodyType.DynamicBody, new Vector2(0.3f, 0)));
}
RevoluteJointDef jointDef = new RevoluteJointDef();
jointDef.localAnchorA.x = -height / 2;
jointDef.localAnchorB.x = height / 2;
RopeJointDef ropeJointDef = new RopeJointDef();
ropeJointDef.localAnchorA.set(0, -height / 2);
ropeJointDef.localAnchorB.set(0, height / 2);
ropeJointDef.maxLength = length;
for(int i = 0; i < length-1; i++) {
jointDef.bodyA = ropeSegmenets.get(i).body;
jointDef.bodyB = ropeSegmenets.get(i + 1).body;
joints[i] = (RevoluteJoint) world.createJoint(jointDef);
ropeJointDef.bodyA = ropeSegmenets.get(i).body;
ropeJointDef.bodyB = ropeSegmenets.get(i+1).body;
ropeJoints[i] = (RopeJoint) world.createJoint(ropeJointDef);
}
}
Screenshots:
Normal:
Stretched:
If you know how to fix this problem, please, help me.
Thanks, Charlie!