- class CRSpring
- {
- private:
- float dx(float v);
- float dv(float x, float v);
- float rk4(float t, float h);
- public:
- float mass, stiffness, damping;
- float time;
- float position;
- float velocity;
- CRSpring();
- void simulate(float timeSteps);
- void reset();
- };
- float CRSpring::dx(float v)
- {
- return v;
- }
- float CRSpring::dv(float x, float v)
- {
- return (-stiffness / mass) * x - (damping / mass) * v;
- }
- float CRSpring::rk4(float t, float h)
- {
- float x = position;
- float v = velocity;
- float dx1 = dx(v);
- float dv1 = dv(x, v);
- x = position + (h / 2.0f) * dx1;
- v = velocity + (h / 2.0f) * dv1;
- float dx2 = dx(v);
- float dv2 = dv(x, v);
- x = position + (h / 2.0f) * dx2;
- v = velocity + (h / 2.0f) * dv2;
- float dx3 = dx(v);
- float dv3 = dv(x, v);
- x = position + h * dx3;
- v = velocity + h * dv3;
- float dx4 = dx(v);
- float dv4 = dv(x, v);
- position = position + (h / 6.0f) * (dx1 + dx2 * 2.0f + dx3 * 2.0f + dx4);
- velocity = velocity + (h / 6.0f) * (dv1 + dv2 * 2.0f + dv3 * 2.0f + dv4);
- return t + h;
- }
- CRSpring::CRSpring()
- {
- reset();
- mass = 0.5f;
- stiffness = 3.0f;
- damping = 2.0f;
- }
- void CRSpring::simulate(float timeSteps)
- {
- time = rk4(time, timeSteps);
- }
- void CRSpring::reset()
- {
- time = 0.0f;
- position = 0.0f;
- velocity = 0.0f;
- }