Documentation
¶
Overview ¶
Package harmonica implements a simplified damped harmonic oscillator. This is ported from Ryan Juckett’s simple damped harmonic motion, originally written in C++.
Example usage:
// Run once to initialize.
spring := NewSpring(FPS(60), 6.0, 0.2)
// Update on every frame.
pos := 0.0
velocity := 0.0
targetPos := 100.0
someUpdateLoop(func() {
pos, velocity = spring.Update(pos, velocity, targetPos)
})
For background on the algorithm see: https://www.ryanjuckett.com/damped-springs/
Index ¶
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
func FPS ¶
FPS returns a time delta for a given number of frames per second. This value can be used as the time delta when initializing a Spring. Note that game engines often provide the time delta as well, which you should use instead of this function, if possible.
Example:
spring := NewSpring(FPS(60), 5.0, 0.2)
Types ¶
type Spring ¶
type Spring struct {
// contains filtered or unexported fields
}
Spring contains a cached set of motion parameters that can be used to efficiently update multiple springs using the same time step, angular frequency and damping ratio.
To use a Spring call New with the time delta (that's animation frame length), frequency, and damping parameters, cache the result, then call Update to update position and velocity values for each spring that neeeds updating.
Example:
// First precompute spring coefficients based on your settings: var x, xVel, y, yVel float64 deltaTime := FPS(60) s := NewSpring(deltaTime, 5.0, 0.2) // Then, in your update loop: x, xVel = s.Update(x, xVel, 10) // update the X position y, yVel = s.Update(y, yVel, 20) // update the Y position
func NewSpring ¶
NewSpring initializes a new Spring, computing the parameters needed to simulate a damped spring over a given period of time.
The delta time is the time step to advance; essentially the framerate.
The angular frequency is the angular frequency of motion, which affects the speed.
The damping ratio is the damping ratio of motion, which determines the oscillation, or lack thereof. There are three categories of damping ratios:
Damping ratio > 1: over-damped. Damping ratio = 1: critlcally-damped. Damping ratio < 1: under-damped.
An over-damped spring will never oscillate, but reaches equilibrium at a slower rate than a critically damped spring.
A critically damped spring will reach equilibrium as fast as possible without oscillating.
An under-damped spring will reach equilibrium the fastest, but also overshoots it and continues to oscillate as its amplitude decays over time.

