I am coding a spring-mass dampener system in Unity and I am having trouble keeping a consistent oscillation. When the damping value is 0, the spring should oscillate indefinitely (while maintaining the same amplitude). All the formulas I am using are checked by a professor, so no issue there. But my spring keeps overshooting or undershooting the amplitude if I leave it running for a while. How can I fix this?
The inaccuracy you’re seeing is likely the result of iterative physics calculations being performed. For an idea of why, consider this:
When you apply spring force, you’re applying as much as the current frame (physics-based, so FixedUpdate()) will provide. As a baseline, that means you should have 1/50-second granularity.
But let’s say you have 1-second granularity instead. The force applied by the spring at each given calculation would be 50 times stronger, when the true, realistic application of force is constantly applied.
This results in forces being applied which will be either stronger or weaker than expected, depending on where the last calculation was made relative to each new one. For instance, when the timing winds up just right, points can be skipped where a strong-enough force would be applied to stop its motion at an end, resulting in a larger range of oscillation.
Inaccuracy will occur as a direct result, with the margin of error reduced by the number of calculations made in the same span of time.
Edit: Added a little more detail