UNPKG

cione-comp-lib

Version:

`$ yarn add cione-comp-lib` 或者 `$ npm i cione-comp-lib -S`

54 lines (53 loc) 2.09 kB
/* @license * Copyright 2020 Google LLC. All Rights Reserved. * Licensed under the Apache License, Version 2.0 (the 'License'); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an 'AS IS' BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ const SETTLING_TIME = 1e4; const MIN_DECAY_MILLISECONDS = 1e-3; const DECAY_MILLISECONDS = 50; class Damper { constructor(decayMilliseconds = DECAY_MILLISECONDS) { this.velocity = 0; this.naturalFrequency = 0; this.setDecayTime(decayMilliseconds); } setDecayTime(decayMilliseconds) { this.naturalFrequency = 1 / Math.max(MIN_DECAY_MILLISECONDS, decayMilliseconds); } update(x, xGoal, timeStepMilliseconds, xNormalization) { const nilSpeed = 2e-4 * this.naturalFrequency; if (x == null || xNormalization === 0) { return xGoal; } if (x === xGoal && this.velocity === 0) { return xGoal; } if (timeStepMilliseconds < 0) { return x; } const deltaX = x - xGoal; const intermediateVelocity = this.velocity + this.naturalFrequency * deltaX; const intermediateX = deltaX + timeStepMilliseconds * intermediateVelocity; const decay = Math.exp(-this.naturalFrequency * timeStepMilliseconds); const newVelocity = (intermediateVelocity - this.naturalFrequency * intermediateX) * decay; const acceleration = -this.naturalFrequency * (newVelocity + intermediateVelocity * decay); if (Math.abs(newVelocity) < nilSpeed * Math.abs(xNormalization) && acceleration * deltaX >= 0) { this.velocity = 0; return xGoal; } else { this.velocity = newVelocity; return xGoal + intermediateX * decay; } } } export { DECAY_MILLISECONDS, Damper, SETTLING_TIME };