Mercurial > hg > beaglert
annotate examples/10-Instruments/airharp/MassSpringDamper.cpp @ 464:8fcfbfb32aa0 prerelease
Examples reorder with subdirectories. Added header to each project. Moved Doxygen to bottom of render.cpp.
author | Robert Jack <robert.h.jack@gmail.com> |
---|---|
date | Mon, 20 Jun 2016 16:20:38 +0100 |
parents | |
children |
rev | line source |
---|---|
robert@464 | 1 /* |
robert@464 | 2 * |
robert@464 | 3 * Simple 1-Dimensional Mass Spring Damper |
robert@464 | 4 * |
robert@464 | 5 * Christian Heinrichs 04/2015 |
robert@464 | 6 * |
robert@464 | 7 */ |
robert@464 | 8 |
robert@464 | 9 #include "MassSpringDamper.h" |
robert@464 | 10 |
robert@464 | 11 MassSpringDamper::MassSpringDamper(float mass, float spring, float damp) { |
robert@464 | 12 |
robert@464 | 13 _dt = 1.0/44100.0; |
robert@464 | 14 _mass = mass; |
robert@464 | 15 _spring = spring; |
robert@464 | 16 _damp = damp; |
robert@464 | 17 _position = 0; |
robert@464 | 18 _velocity = 0; |
robert@464 | 19 |
robert@464 | 20 } |
robert@464 | 21 |
robert@464 | 22 void MassSpringDamper::setup() { |
robert@464 | 23 |
robert@464 | 24 } |
robert@464 | 25 |
robert@464 | 26 double MassSpringDamper::update(float inForce) { |
robert@464 | 27 |
robert@464 | 28 // 1. calculate spring/damper forces using current position and velocity |
robert@464 | 29 |
robert@464 | 30 double out = (_position * (double)_spring * -1) + (_velocity * (double)_damp * -1); |
robert@464 | 31 |
robert@464 | 32 // 2. apply external force |
robert@464 | 33 |
robert@464 | 34 out += inForce; |
robert@464 | 35 |
robert@464 | 36 // 3. derive acceleration (a = f/m) |
robert@464 | 37 |
robert@464 | 38 out /= (double)_mass; |
robert@464 | 39 |
robert@464 | 40 // 4. derive velocity (v = a*dt) |
robert@464 | 41 |
robert@464 | 42 out *= _dt; |
robert@464 | 43 |
robert@464 | 44 // 5. apply previous velocity |
robert@464 | 45 |
robert@464 | 46 out += _velocity; |
robert@464 | 47 |
robert@464 | 48 // 6. save current velocity state for next iteration |
robert@464 | 49 |
robert@464 | 50 _velocity = out; |
robert@464 | 51 |
robert@464 | 52 // 7. derive new position (x[n] = x[n-1] + v[n]) and save for next iteration |
robert@464 | 53 |
robert@464 | 54 out += _position; |
robert@464 | 55 _position = out; |
robert@464 | 56 |
robert@464 | 57 return out; |
robert@464 | 58 |
robert@464 | 59 } |