If
all you need is rope stuff (and you don't need a full rigid body simulator), Verlet integration plus distance constraints by position projection is the simplest approach, and it's pretty fast. For each particle you store the current position and the last position, and time stepping is done as follows, where ax is the x component of the acceleration, assuming a fixed time step:
Code: Select all
float xBuffer = x;
x = 2*x - xLast + ax*deltaTSquared;
xLast = xBuffer;
Do the same for the y coords. You also need constraints, which look more or less like this, where pA and pB are the two particles, and you're trying to keep them a constant distance apart (distanceSqr is the desired distance squared):
Code: Select all
float myDistSqr = pA.position.distanceSqr(pB.position);
float alpha = sqrt(distanceSqr/ (myDistSqr + .001)); //ok if distanceSqr == 0, since alpha is then zero
float oneminusalpha = 1.0-alpha;
float oneoversum = 1.0/(pA.mass + pB.mass);
float cmx = (pA.mass*pA.position.x + pB.mass*pB.position.x) * oneoversum;
float cmy = (pA.mass*pA.position.y + pB.mass*pB.position.y) * oneoversum;
pA.position.x = cmx*oneminusalpha + alpha*pA.position.x;
pA.position.y = cmy*oneminusalpha + alpha*pA.position.y;
pB.position.x = cmx*oneminusalpha + alpha*pB.position.x;
pB.position.y = cmy*oneminusalpha + alpha*pB.position.y;
I didn't optimize this completely, so you may be able to clean it up a bit by playing with the algebra. If you make a whole string of particles and then loop through them applying this constraint (you may have to do several iterations of the constraints, more will lead to a tighter, less springy rope), you'll end up with a fairly reasonable rope, much better than you'll get if you do a particle + spring simulation. If you're pinning one end of a rope to a wall, I would suggest setting the mass of the pinned particle to a fairly high value and applying the constraints starting from that end, as it should speed up the convergence a bit.
If you need more, you can even try connecting springs to every other particle (i.e. a spring between particles 0 and 2, 1 and 3, etc) and/or every third particle, which will give the rope a bit of stiffness. Once you start adding springs, you need to watch your spring constants lest you run into stability issues; pure position projection + Verlet integration should be almost unconditionally stable without the springs, though, at least for a rope configuration.
This is not the ideal approach for more general physics, though, so don't try to build a full featured rigid body engine out of these types of particle systems...