#22 - Spring Damping class

Data: 2018-08-18 12:00 - C++

Spring Damping class for use in game animations.

// SpringDamping.h
#pragma once

namespace GameEngine {
	namespace Physics {
		template<typename T>
		class SpringDamping {
			T old;
			float _springConstant;
			float _damping;
			T* current;
			T* target;
		public:
			SpringDamping(float springConstant, float damping, T* current, T* target);
			void update(float dtime);
		};
	}
}

// SpringDamping.cpp
#include "SpringDamping.h"

#include <glm/glm.hpp>

using namespace GameEngine::Physics;

template SpringDamping<glm::vec2>;

template<typename T> SpringDamping<T>::SpringDamping(float springConstant, float damping, T* current, T* target)
		: _springConstant(springConstant), _damping(damping), current(current), target(target), old(*current) {
}

template<typename T> void SpringDamping<T>::update(float dtime) {
	T velocity = *current - old;
	T displacement = (*target - *current);
	old = *current;
	*current = *current + displacement * dtime + _damping * velocity;
}

Previous snippet | Next snippet