Springs

Springs

Somewhere between the ixfx forces and oscillators are springs.

For a typical use of a spring, use Oscillators.spring.

Like the other oscillators, it returns a generator. It generally returns values between 0..1, however depending on its settings, it might over-shoot the ends, for example returning 1.1.

import { Oscillators } from "https://unpkg.com/ixfx/dist/modulation.js"

// Init spring
const spring = Oscillators.spring();

// Animation loop
const loop = () => {
  // Yields relative values ~0...~1
  //  or undefined when spring has stopped
  const v = spring.next().value;

  setTimeout(loop, 1);
}
loop();

Each time the loop function runs, v will have the value of the spring, or return undefined if the spring has finished.

The value of the spring can be applied to anything. In the demo, it is used to calculate a position for the ring.

// Point where spring was sprung
const fromPoint = { x: 0, y: 0 };
// Destination
const toPoint = { x: 1, y: 1 };

// Interpolate to get an in-between point.
// Since spring can overshoot 0..1, we pass in _true_ at
// for interpolate to allow this.
const pos = Points.interpolate(v, fromPoint, toPoint, true);

There are some options for Oscillators.spring for tweaking its behaviour.

const spring = Oscillators.spring({
 mass: 5,        // Weight of thing at end of spring
 damping: 10,    // Energy loss as we move
 stiffness: 100,
 velocity: 0.1   // Multiplier for velocity
});