Created
September 6, 2022 15:33
-
-
Save mrchaofan/829d8a5df81bea637bc51aa568f7a763 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
export interface IStepOptions { | |
secondsPerFrame?: number; | |
v: number; | |
x: number; | |
destX: number; | |
k: number; | |
b: number; | |
precision?: number; | |
} | |
export default function stepper({ | |
secondsPerFrame = 1 / 60, | |
v, | |
x, | |
destX, | |
k, | |
b, | |
precision = 0.01 | |
}: IStepOptions): Required<IStepOptions> { | |
const fSpring = -k * (x - destX); | |
const fDamper = -b * v; | |
const a = fSpring + fDamper; | |
const newV = v + a * secondsPerFrame; | |
const newX = x + newV * secondsPerFrame; | |
if (Math.abs(newV) < precision && Math.abs(newX - destX) < precision) { | |
return { | |
secondsPerFrame, | |
v: 0, | |
x: destX, | |
destX, | |
k, | |
b, | |
precision | |
}; | |
} | |
return { | |
secondsPerFrame, | |
v: newV, | |
x: newX, | |
destX, | |
k, | |
b, | |
precision | |
}; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment