struct

Harmonica::Spring

Inherits Struct < Value < Object

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 (animation frame length), frequency, and damping parameters, cache the result, then call #update to update position and velocity values for each spring that needs updating.

Example:

# First precompute spring coefficients based on your settings:
delta_time = Harmonica.fps(60)
spring = Spring.new(delta_time, 5.0, 0.2)

# Then, in your update loop:
x, x_vel = spring.update(x, x_vel, 10) # update the X position
y, y_vel = spring.update(y, y_vel, 20) # update the Y position

Constructors

new(delta_time : Float64, angular_frequency : Float64, damping_ratio : Float64)

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: critically-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.

Source

Instance methods

pos_pos_coef

Position coefficient for position

Source
pos_vel_coef

Velocity coefficient for position

Source
update(pos : Float64, vel : Float64, equilibrium_pos : Float64) : Tuple(Float64, Float64)

Updates position and velocity values against a given target value. Call this after calling .new to update values.

Source
vel_pos_coef

Position coefficient for velocity

Source
vel_vel_coef

Velocity coefficient for velocity

Source