Tick source

This commit is contained in:
Tangent Wantwight 2024-01-23 23:29:11 -05:00
parent 73fc6bf3f0
commit 7d25c3e676
1 changed files with 36 additions and 0 deletions

36
lib/tick.ts Normal file
View File

@ -0,0 +1,36 @@
import { Cancel, Source } from "./source";
export type PhysicsTick = ["physics"];
export type RenderTick = ["render", number];
export function tick(fps: number): Source<PhysicsTick | RenderTick> {
function tickSource(): PhysicsTick;
function tickSource(
callback: (tick: PhysicsTick | RenderTick) => void
): Cancel;
function tickSource(callback?: (tick: PhysicsTick | RenderTick) => void) {
if (callback) {
let lastPhysicsTick: number = new Date().getTime();
const physicsInterval = setInterval(() => {
lastPhysicsTick = new Date().getTime();
callback(["physics"]);
}, 1000 / fps);
let animationFrame = requestAnimationFrame(function animationTick() {
const now = new Date().getTime();
callback(["render", now - lastPhysicsTick]);
animationFrame = requestAnimationFrame(animationTick);
});
return () => {
clearInterval(physicsInterval);
cancelAnimationFrame(animationFrame);
};
} else {
return ["physics"];
}
}
return tickSource;
}