4

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

fancyPants
  • 50,732
  • 33
  • 89
  • 96
Rajesh
  • 41
  • 1
  • 2

2 Answers2

5

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;
Community
  • 1
  • 1
Pavel
  • 2,602
  • 1
  • 27
  • 34
  • Thanks, now second part of the problem...why there is no any distance joint formed between two bodies...is there any problem in the code...i can post more code if necesssary... – Rajesh Feb 07 '13 at 08:32
  • for refernce this is my main function-> '$(function() { world = createWorld(); canvas = document.getElementById('game'); ctx = canvas.getContext('2d'); canvas_width = parseInt(canvas.width); canvas_height = parseInt(canvas.height); createGround(canvas_width / 2, canvas_height - iBorder, canvas_width / 2, iBorder, 0); Body1 = CreateObject1(); Body2 = CreateObject2(); CreateJoint(); $(canvas).mousedown(function() { ChangePosition(); }); frame(); });' – Rajesh Feb 07 '13 at 08:50
  • Tell please, what returns CreateJoint method. – Pavel Feb 07 '13 at 13:15
0

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

Rajesh
  • 41
  • 1
  • 2