Game Development Reference
/** Creates a new spring with the given parameters. */
real springConstant, real restLength);
/** Applies the spring force to the given particle. */
virtual void updateForce(Particle *particle, real duration);
Excerpt from src/pfgen.cpp
void ParticleAnchoredSpring::updateForce(Particle* particle,
// Calculate the vector of the spring.
force -= *anchor;
// Calculate the magnitude of the force.
real magnitude = force.magnitude();
magnitude = real_abs(magnitude - restLength);
magnitude *= springConstant;
// Calculate the final force and apply it.
force *= -magnitude;
If we wanted to connect the game's camera to the player's character, this is an
approach we would use. Instead of an anchor point that never moves, however, we
would recalculate and reset the anchor point at each frame based on the position
of the character. The previous implementation needs no modification (other than a
setAnchor method to give the new value); we would just need to perform the update
of the anchor point somewhere in the game loop.
A N E LASTIC B UNGEE G ENERATOR
An elastic bungee only produces pulling forces. You can scrunch it into a tight ball
and it will not push back out, but it behaves like any other spring when extended.
This is useful for keeping a pair of objects together: they will be pulled together if
they stray too far, but they can get as close as they like without being separated.