chris@164: /* chris@164: * chris@164: * Simple 1-Dimensional Mass Spring Damper chris@164: * chris@164: * Christian Heinrichs 04/2015 chris@164: * chris@164: */ chris@164: chris@164: #include "MassSpringDamper.h" chris@164: chris@164: MassSpringDamper::MassSpringDamper(float mass, float spring, float damp) { chris@164: chris@164: _dt = 1.0/44100.0; chris@164: _mass = mass; chris@164: _spring = spring; chris@164: _damp = damp; chris@164: _position = 0; chris@164: _velocity = 0; chris@164: chris@164: } chris@164: chris@164: void MassSpringDamper::setup() { chris@164: chris@164: } chris@164: chris@164: double MassSpringDamper::update(float inForce) { chris@164: chris@164: // 1. calculate spring/damper forces using current position and velocity chris@164: chris@164: double out = (_position * (double)_spring * -1) + (_velocity * (double)_damp * -1); chris@164: chris@164: // 2. apply external force chris@164: chris@164: out += inForce; chris@164: chris@164: // 3. derive acceleration (a = f/m) chris@164: chris@164: out /= (double)_mass; chris@164: chris@164: // 4. derive velocity (v = a*dt) chris@164: chris@164: out *= _dt; chris@164: chris@164: // 5. apply previous velocity chris@164: chris@164: out += _velocity; chris@164: chris@164: // 6. save current velocity state for next iteration chris@164: chris@164: _velocity = out; chris@164: chris@164: // 7. derive new position (x[n] = x[n-1] + v[n]) and save for next iteration chris@164: chris@164: out += _position; chris@164: _position = out; chris@164: chris@164: return out; chris@164: chris@164: }