Implement multiple solvers for damped harmonic oscillator.
Solvers:
- Closed-form solution for the ODE
- Semi-implicit Euler method
- Explicit Runge-Kutta 4th order aka RK4
- Verlet Integration
Maybe not:
- Explicit Euler aka Forward Euler
- Implicit Euler aka Backward Euler
- Mid-point method
- Implicit Runge-Kutta 4th order aka RK4
Performance rough check with 2.6 GHz Intel Core i7:
via Package Manager UI
ssh://git@github.com/thammin/unity-spring.git
via OpenUPM
openupm add com.thammin.unity-spring
Every solver is just a simple class with few fields.
using UnityEngine;
using Spring = UnitySpring.ClosedForm.Spring;
public class Ball : MonoBehaviour
{
Spring spring;
void Start()
{
// interpolate from -10f to 10f
spring = new Spring()
{
startValue = -10f,
endValue = 10f
};
}
void Update()
{
var x = spring.Evaluate(Time.deltaTime);
transform.position = new Vector3(x, 0f, 0f);
}
}
Visualizer:
Source code: link
Based on closed-form solution, but only modeling critically damped spring. Using tweaked Exponential approximation (up to Taylor 3rd order) which claims as roughly 80 times faster and approximate less than 0.1% error than exp
function.
// tweaked coefficients
float exp = 1F / (1F + x + 0.48F * x * x + 0.235F * x * x * x);
Analytical:
- http://www.entropy.energy/scholar/node/damped-harmonic-oscillator
- https://doc.lagout.org/Others/Game%20Development/Programming/Game%20Programming%20Gems%204.pdf
Numerical:
General:
MIT