Mercurial > hg > beaglert
annotate projects/airharp/MassSpringDamper.cpp @ 164:40badaff5729 heavy-updated
- added more pd/heavy examples
- removed heavy-specific flags from Makefile
- added air-harp cpp example project
author | chnrx <chris.heinrichs@gmail.com> |
---|---|
date | Thu, 03 Dec 2015 16:19:33 +0000 |
parents | |
children |
rev | line source |
---|---|
chris@164 | 1 /* |
chris@164 | 2 * |
chris@164 | 3 * Simple 1-Dimensional Mass Spring Damper |
chris@164 | 4 * |
chris@164 | 5 * Christian Heinrichs 04/2015 |
chris@164 | 6 * |
chris@164 | 7 */ |
chris@164 | 8 |
chris@164 | 9 #include "MassSpringDamper.h" |
chris@164 | 10 |
chris@164 | 11 MassSpringDamper::MassSpringDamper(float mass, float spring, float damp) { |
chris@164 | 12 |
chris@164 | 13 _dt = 1.0/44100.0; |
chris@164 | 14 _mass = mass; |
chris@164 | 15 _spring = spring; |
chris@164 | 16 _damp = damp; |
chris@164 | 17 _position = 0; |
chris@164 | 18 _velocity = 0; |
chris@164 | 19 |
chris@164 | 20 } |
chris@164 | 21 |
chris@164 | 22 void MassSpringDamper::setup() { |
chris@164 | 23 |
chris@164 | 24 } |
chris@164 | 25 |
chris@164 | 26 double MassSpringDamper::update(float inForce) { |
chris@164 | 27 |
chris@164 | 28 // 1. calculate spring/damper forces using current position and velocity |
chris@164 | 29 |
chris@164 | 30 double out = (_position * (double)_spring * -1) + (_velocity * (double)_damp * -1); |
chris@164 | 31 |
chris@164 | 32 // 2. apply external force |
chris@164 | 33 |
chris@164 | 34 out += inForce; |
chris@164 | 35 |
chris@164 | 36 // 3. derive acceleration (a = f/m) |
chris@164 | 37 |
chris@164 | 38 out /= (double)_mass; |
chris@164 | 39 |
chris@164 | 40 // 4. derive velocity (v = a*dt) |
chris@164 | 41 |
chris@164 | 42 out *= _dt; |
chris@164 | 43 |
chris@164 | 44 // 5. apply previous velocity |
chris@164 | 45 |
chris@164 | 46 out += _velocity; |
chris@164 | 47 |
chris@164 | 48 // 6. save current velocity state for next iteration |
chris@164 | 49 |
chris@164 | 50 _velocity = out; |
chris@164 | 51 |
chris@164 | 52 // 7. derive new position (x[n] = x[n-1] + v[n]) and save for next iteration |
chris@164 | 53 |
chris@164 | 54 out += _position; |
chris@164 | 55 _position = out; |
chris@164 | 56 |
chris@164 | 57 return out; |
chris@164 | 58 |
chris@164 | 59 } |