auto-accept/js/flywheel.js

66 lines
1.9 KiB
JavaScript

/*
The interface is like a flywheel.
*/
export class Flywheel{
constructor() {
this.value = 0.; // start at 0 - gradual meter
this.stage = 0.; // start at 0 - the various stages
this.f_falloff = (value) => value/20; // value at which it reduces per second
this.f_stage = (value) => 5*Math.log10(value); // value to stage calculation
this.value_min = 0;
this.value_max = 100; // gives stage 0-9
// this.interval = window.setInterval(this.step, 50)
this.time = null;
window.requestAnimationFrame(this.step.bind(this));
// TODO: once/twice per second should be enough! + on release (add())
}
step(time){
if(this.time === null){
// first run
this.time = time;
window.requestAnimationFrame(this.step.bind(this));
return;
}
if(time-this.time < 500){
window.requestAnimationFrame(this.step.bind(this));
return;
}
const dt = time - this.time;
this.time = time;
this.value -= this.f_falloff(this.value) * dt/1000; // linear falloff
if(this.value < 0){
this.value = 0;
}
// console.log(this.value,this.falloff, dt,this.time);
// TODO: check if this should be different
const stage = Math.max(0,Math.floor(this.f_stage(this.value)));
if (stage != this.stage){
this.changeStage(stage);
}
window.requestAnimationFrame(this.step.bind(this));
}
add(increment){
this.value += typeof increment == 'undefined' ? 1 : increment;
// cap:
if(this.value > this.value_max) this.value = this.value_max;
}
changeStage(stage){
this.stage = stage;
console.log('stage now at', this.stage);
// TODO: handle stage change
}
}