request: some kind of elastic spring

i don't think that this one exists, so a new joint between two objects would be fine: when i shoot a ball into another ball i want to put them together with some kind of elastic rope - in other words some kind of distance joint with a static length (regarding to the object's velocity). is this already somehow implemented? if not: are there any plans for implementing this feature in future releases?
If the spring is soft you can use Hooke's law: http://en.wikipedia.org/wiki/Hooke's_law. Things like soft springs, air drag, etc, should be implemented by the user using forces. These sorts of forces are often easy to code and/or application specific.

If you need a stiff (but not rigid) spring then that would be an enhancement of the distance joint. Let me know if you need this.
Erin Catto wrote:If the spring is soft you can use Hooke's law: http://en.wikipedia.org/wiki/Hooke's_law. Things like soft springs, air drag, etc, should be implemented by the user using forces. These sorts of forces are often easy to code and/or application specific.

If you need a stiff (but not rigid) spring then that would be an enhancement of the distance joint. Let me know if you need this.

hmmm... i need some kind of spring between two (or more) moving bodies. a movie of what i'm planning to do should be located here: http://www.bigfishgames.com/download-ga ... index.html (simply click on "watch video" - i hope that you see what happens when two or more balls with the same color collide. unfortunately i can't watch the movie now, since the company's firewall doesn't like movies at all 😉)

additionally i have no idea if (and how) this issue can be solved by the use of forces (or how i transform these funny formulas into c++-code 😉).

and: thanks for box2d, almighty mr catto! when i'm able to solve my spring-thingie too your physics-engine gives me pretty everything i need! 🙂
This is probably a good case where a contributed library would be welcome, covering things like springs, drag, planetary gravity, e/m forces, and that type of good stuff, especially if it was done in a user-friendly way.

Hierro - you can definitely do what you want with a Hooke's law spring. I don't have my Box2d code in front of me so I can't explain how to code it at the moment, but if I have time I'll try to put together a simple example (no promises it will be today, I'm pretty busy). The gist of it is:

1) Get the distance between particles.
2) Subtract the desired distance from 1), call the result deltaX.
3) Calculate -kSpring*deltaX.
4) Apply a force with magnitude calculated in 3) along the straight line between the particles.

If you want damping it gets trickier, see the Wikipedia page Erin posted before.
Ok, I had a bit of time. 🙂

This is code for JBox2D, so it won't run as-is in Box2D, you'll need to translate it from Java to C++ and add b2 prefixes where appropriate (i.e. Vec2 -> b2Vec2, Body -> b2Body) - I'd do the changes myself, but that would imply it would actually run and I haven't had a chance to test it in C++. Some of the method names might have to be capitalized, too. This does work in Java, you just call it once a frame with the desired parameters. Ask away if you have trouble.

Code: Select all

    public void addSpringForce(Body bA, Body bB, float k, float friction, float desiredDist) {
        Vec2 pA = bA.m_position;
        Vec2 pB = bB.m_position;
        Vec2 diff = pB.sub(pA);
        Vec2 vA = bA.m_linearVelocity;
        Vec2 vB = bB.m_linearVelocity;
        Vec2 vdiff = vB.sub(vA);
        float dx = diff.normalize(); //normalizes diff and puts length into dx
        float vrel = vdiff.x*diff.x + vdiff.y*diff.y;
        float forceMag = -k*(dx-desiredDist) - friction*vrel;
        diff.mulLocal(forceMag); // diff *= forceMag
        bB.applyForce(diff, bA.m_position);
        bA.applyForce(diff.mulLocal(-1f), bB.m_position);
        bA.wakeUp();
        bB.wakeUp();
       
        //Draw spring - you'll need to put your own code here, probably
        //line(bA.m_position.x, bA.m_position.y, bB.m_position.x, bB.m_position.y);
    }


For a first try, I'd put k somewhere around 500-1000 and friction (damps the oscillations) between 1 and 10 - it all depends on the masses of the objects and the scale of your simulation, really.

This only applies the force at the center of mass of the object. Sorry, to apply to an arbitrary point is a little trickier and I don't have enough time to work it out at the moment.

Erin, you probably don't need a special stiff spring, I found that with a good choice of damping and spring constant you can make a spring that is almost indistinguishable from a true distance joint. Should be good enough for almost any purpose other than an actual distance joint...
thank you for your efforts... 🙂

...but i fear that's not everything i need. i want two objects to be linked together with some kind of joint (= spring) and vary the length of the joint (= length of the spring) depending on collisions between objects (the two object being linked together and a few others in the world). some kind of distance joint with some kind of dynamic distance or something 😉
Hmm, I think I might be misinterpreting what you want - as I understand your goal, you should be able to achieve it by just calling the function I posted with whatever distance you want at a given moment (to figure out what distance you want is up to you, that is a question of game design). As it's set up, there's no need for the distance passed to that function to be the same each frame (it's not persistent at all, you have to actually call it every frame). For instance, if you wanted a sinusoidal time dependence, once per frame you'd write something like (assuming t is the time variable):

Code: Select all

float currentDistance = scale * ( sin(2*PI*t*frequency) + 1 ) * .5f;
addSpringForce(ballA, ballB, 500, 1, currentDistance);


If you want to make the distance dependent on other variables, you're free to do so, though you'll have to work out the bookkeeping to suit your particular game. I'm not sure I can help much there, since it depends crucially on the details of your implementation, but feel free to ask if you have trouble.
Sorry to bump an old topic, but I altered the spring code so that you can attach springs at arbitrary points on each body:

Code: Select all

/*
 * Adds a damped Hooke's law spring force between bodies bA and bB,
 * attached at body local coordinates localA and localB.
 */
    public void addSpringForce(Body bA, Vec2 localA, Body bB, Vec2 localB, float k, float friction, float desiredDist) {
        Vec2 pA = bA.getWorldPoint(localA);
        Vec2 pB = bB.getWorldPoint(localB);
        Vec2 diff = pB.sub(pA);
        //Find velocities of attach points
        Vec2 vA = bA.m_linearVelocity.sub(Vec2.cross(bA.getWorldVector(localA), bA.m_angularVelocity));
        Vec2 vB = bB.m_linearVelocity.sub(Vec2.cross(bB.getWorldVector(localB), bB.m_angularVelocity));
        Vec2 vdiff = vB.sub(vA);
        float dx = diff.normalize(); //normalizes diff and puts length into dx
        float vrel = vdiff.x*diff.x + vdiff.y*diff.y;
        float forceMag = -k*(dx-desiredDist) - friction*vrel;
        diff.mulLocal(forceMag); // diff *= forceMag
        bB.applyForce(diff, bA.getWorldPoint(localA));
        bA.applyForce(diff.mulLocal(-1f), bB.getWorldPoint(localB));
        bA.wakeUp();
        bB.wakeUp();
  }

This is JBox2d code, but C++ and AS3 translations should be fairly easy if you need them.

Edit: I got a C++ testbed file working, so I'll attach that, too.
Here's another Springs.h demo file - I made up a Jello cube by connecting a bunch of bodies with springs.

This is not the way you should do soft bodies if that's what you're after, because it takes a ton of tuning to get the spring constants and connectivities right, and it's extremely inefficient.

It makes for an interesting demo, nevertheless.

@Erin: Stability issues abound when using position dependent forces like this, especially when not applying them at the center of mass; would this be helped by implementing Hooke springs as a joint type? If so, I might see if I can find the time to do this - do your old Box2d lite talks cover how to get from a force law to a joint implementation?
Box2D uses symplectic Euler, which is stable for roughly medium stiffness problems. For stiffer problems, like vehicle suspensions, I recommend using a soft distance constraint. In Box2D_Lite you will find a soft revolute constraint used for the suspension bridge. It should be straight forward to use the same technique for a soft distance constraint.

Original thread: https://box2d.org/forum/viewtopic.php?t=116