Rajesh
Rajesh

Reputation: 41

spring effect in box2djs

I want to simulate spring effect using box2djs. After a lot search i figure it that that distancejoint can be used (i am not sure). I tried the follwing code but i am not looking any joint between the body.

 distance_joint = new b2DistanceJointDef();

distance_joint.body1 = Body1;

distance_joint.body2 = Body2;

distance_joint.localAnchorA = new b2Vec2(0, 0);

distance_joint.localAnchorB = new b2Vec2(0, 0);

distance_joint.length = 3;

distance_joint.collideConnected = true;

return world.CreateJoint(distance_joint); 

Any idea...

Thanks

Upvotes: 4

Views: 5764

Answers (2)

Rajesh
Rajesh

Reputation: 41

CreateJoint returns b2Joint(the joint created), but that is not the issue... I found out the issue. Actually i was setting local anchor point as

distance_joint.localAnchorA = new b2Vec2(0, 0);

distance_joint.localAnchorB = new b2Vec2(0, 0);

rather i should created the anchor point in the world like

distance_joint.anchorPoint1.Set(0.0, 0.0);

distance_joint.anchorPoint2.Set(0.0, 0.0);

Now, the joint is created correctly. One more issue...since i am trying to implement spring effect i try to set anchor point in the middle of the sencond body, but i am not getting success.

any idea..

Thanks

Upvotes: 0

Pavel
Pavel

Reputation: 2554

You are right, distance joint can be used as the spring. This is said in the Box2D manual:

The distance joint can also be made soft, like a spring-damper connection. See the Web example in the testbed to see how this behaves.

Softness is achieved by tuning two constants in the definition: frequency and damping ratio. Think of the frequency as the frequency of a harmonic oscillator (like a guitar string). The frequency is specified in Hertz. Typically the frequency should be less than a half the frequency of the time step. So if you are using a 60Hz time step, the frequency of the distance joint should be less than 30Hz. The reason is related to the Nyquist frequency.

The damping ratio is non-dimensional and is typically between 0 and 1, but can be larger. At 1, the damping is critical (all oscillations should vanish).

jointDef.frequencyHz = 4.0f;
jointDef.dampingRatio = 0.5f;

Upvotes: 5

Related Questions