Let's say I have a 1-dimensional spring, and I want to simulate it by applying a force that may vary with time. We can skip friction and dampeners for now.
From what I learned many years ago in high school physics, one can apply Hooke's law and calculate the resulting force, which can be applied to calculate the resulting displacement.
Here's a trivial snippet that in principle does just that:
float spring = stiffness * displacement;
float totalForce = force - spring;
displacement += (velocity * deltaTime) + (totalForce * deltaTime * deltaTime / 2.0f);
velocity += totalForce * deltaTime;
I'm over simplifying some things, like the mass of the spring, and this is by design. I'd rather have a simple system than a complex one that is perfectly physically accurate.
With a non-zero initial displacement, and zero force, this should oscillate in place. However, when I actually go and simulate it, the oscillation magnitude grows and grows infinitely.
I tried plotting this, and this is the result:
I'm reading some stuff online, and it seems like this method is infamous for being unstable, although it's not really clear to me why.
I'll continue researching, but is there a way to fix my method so it's more stable, or alternatively, is there a known simple, stable method to simulate something that looks like a spring? Once again, simplicity is more important than perfect accuracy.

