diff --git a/lib/tick.ts b/lib/tick.ts new file mode 100644 index 0000000..9a2161a --- /dev/null +++ b/lib/tick.ts @@ -0,0 +1,36 @@ +import { Cancel, Source } from "./source"; + +export type PhysicsTick = ["physics"]; +export type RenderTick = ["render", number]; + +export function tick(fps: number): Source { + 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; +}