2024.js/lib/tick.ts

33 lines
978 B
TypeScript
Raw Normal View History

2024-01-27 23:57:09 -05:00
import { Source } from "./source";
2024-01-23 23:29:11 -05:00
export type PhysicsTick = ["physics"];
export type RenderTick = ["render", number];
export function tick(fps: number): Source<PhysicsTick | RenderTick> {
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();
2024-01-23 23:54:30 -05:00
callback(["render", (now - lastPhysicsTick) / 1000]);
2024-01-23 23:29:11 -05:00
animationFrame = requestAnimationFrame(animationTick);
});
return () => {
clearInterval(physicsInterval);
cancelAnimationFrame(animationFrame);
};
} else {
return ["physics"];
}
}
2024-01-27 23:57:09 -05:00
return tickSource as Source<PhysicsTick | RenderTick>;
2024-01-23 23:29:11 -05:00
}