Damped Spring Oscillations in JavaScript: A bit of code and a fun simulation.

posted 2012-Oct-4

For work I needed to simulate the behavior a whip antenna springing back and forth. Following is some JavaScript code simulating a damped spring.

The core code that you need to run each frame:

newVelocity  = oldVelocity * ( 1 - damping );             // 0:no damping; 1:full damping
newVelocity -= (oldPosition-restValue) * springTension;   // The force to pull it back to the resting point
newPosition  = oldPosition + newVelocity;


The important thing here is to keep track of the velocity, since the damping needs to be proportional to the velocity, and the spring force modifies the velocity of the object (not the position).