How do I reset a Box2d RevoluteJoint to its original state properly?

105 Views Asked by At

I have a world with a static body (B) and a dynamic body (A) connected through a RevoluteJoint (j). After having the simulation run through a number of frames I reset the bodies and joint by:

    private void reset(){
        //PPM = 32
        A.setTransform(30 / PPM, 30 / PPM, 0); //Putting the bodies back to their original positions and rotations
        B.setTransform(50 / PPM, 20 / PPM, 0);

        A.setAngularVelocity(0);//Reset Angular Velocity
        B.setAngularVelocity(0);

        A.setLinearVelocity(0, 0);//Reset Linear Velocity
        B.setLinearVelocity(0, 0);

        j.setMotorSpeed(10);//Set motor speed
        j.setMaxMotorTorque(1);//Set maximum torque
    }

I log the jointAngle() of the joint in every frames after each reset and the values are slightly different each time the loop is simulated. For example:

Frame Loop 1 Loop 2 Loop 3
0 Angle: 0.0 Angle: 0.046254314 Angle: 0.046254314
1 Angle: 0.046254348 Angle: 0.13844918 Angle: 0.13844918
2 Angle: 0.1384492 Angle: 0.27575454 Angle: 0.27575454
3 Angle: 0.2757546 Angle: 0.45236742 Angle: 0.45236757

I think there are some values of the joint that are retained after each reset. But I'm not entirely sure if it has something to do with the getMotorTorque() value of the joint. It doesn't seem to be random either because I don't think box2d uses random numbers for their calculations.

After digging around for a while I found a similar question. However it didn't seem to answer the same problem I had. So, is there any way I can completely reset the joint (and bodies) with 100% accuracy, without destroying and recreating them after each loop?

1

There are 1 best solutions below

1
On

I don't know exactly what your problem is, but I can give you some tips that might help you.

1.Try this

A.setTransform(0, 0, 0);
b.setTransform(0, 0, 0);
A.setTransform(30/PPM, 30/PPM, 0);
b.setTransform(50/PPM, 20/PPM, 0);

instead of

A.setTransform(30/PPM, 30/PPM, 0);
b.setTransform(50/PPM, 20/PPM, 0);

This way you first set the desired angle (0) and then set the desired position (50/PPM, 20/PPM). If you try to set the angle and position at the same time, it may not work (I encountered it personally)

  1. Try turning off the link motor and see if the problem persists

  2. Try disabling the connection completely (j.setActive(false) or something like this) (this will help you understand if the problem is with the connection)