From 7d25c3e6762fa122245fb5e3328474f0d1e97326 Mon Sep 17 00:00:00 2001 From: Tangent Wantwight Date: Tue, 23 Jan 2024 23:29:11 -0500 Subject: [PATCH] Tick source --- lib/tick.ts | 36 ++++++++++++++++++++++++++++++++++++ 1 file changed, 36 insertions(+) create mode 100644 lib/tick.ts 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; +}