当我使用绳索时,我正在开发一个游戏,这是我在 Box2d 中使用圆圈和关节创建的。当我用低力拖动绳索时,绳索按预期工作,而在其他情况下(当力更大时)它就像疯了一样伸展,我不知道如何修复它并创造更稳定的绳索。我尝试了不同类型的关节(RopeJoint、RevoluteJoint、DistanceJoint 等),但没用。这是我的代码:
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);
}
}
截图:
普通的:
拉伸:
如果您知道如何解决此问题,请帮助我。
谢谢,查理!