1
votes

I am trying to create a pendulum using box2d/libgdx by connecting a static and a dynamic body. I have tried various types of joints like distance joint, rope joint and revolute joint but under gravity the dynamic body always ends up escaping down after initially being constrained by the joint. Only in zero gravity the joints work properly. I know I must be doing something really silly.

       world.getBodies(p);
       DistanceJointDef djd=new DistanceJointDef();
       djd.bodyA=p.get(0);
        djd.bodyB=p.get(1);
        djd.localAnchorA.set(0,0);
        djd.localAnchorB.set(0,0);
        djd.collideConnected=true;
               DistanceJoint pend=(DistanceJoint)world.createJoint(djd);   
        pend.setLength(50);

PS. I have to yet implemented a contact listener .I have not figured out how to do this. Will putting up a collision listener help?

2
Does your dynamic body have a nonzero density?user3312130

2 Answers

0
votes

If I get your question correctly, your moving body falls irrespective of the type of joint you applied. One reason why that could happen is because you may have defined both the anchor and pendulum as dynamic bodies, and both fall the same way due to gravity.

I am assuming you are not yet rendering the anchor body, so you do not see it falling.

1
votes

I tried your exact code and it works. Here's the full test:
@user3312130: It works with a density of zero as well.

Make sure you step the world with at least one velocity iteration. When I used zero, the joint slowly expanded.

A ContactListener has not really anything to do with this, it won't help.

Another thing: You set the length of the DistanceJoint to 50 meters. That's a pretty big distance. Box2D is optimized for 1x1 meter objects. It will still work and I tested it, but you should probably use way smaller objects and a smaller camera viewport.