Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Binary file modified bun.lockb
Binary file not shown.
4 changes: 2 additions & 2 deletions src/game/time.system.tsx
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { useRef } from "react";
import { useAnimationFrame } from "~/hooks/useAnimationFrame";
import { useTimeout } from "~/hooks/useTimeout";
import { useSettingsStore } from "~/store/settings.store";
import { useWorldStore } from "~/store/world.store";
import { TICK_MS } from "./const";
Expand All @@ -13,7 +13,7 @@ export function TimeSystem() {
const paused = useSettingsStore((state) => state.paused);
const speed = useSettingsStore((state) => state.speed);

useAnimationFrame((dt) => {
useTimeout((dt) => {
if (paused) return;

const time = timeRef.current + dt * speed;
Expand Down
28 changes: 0 additions & 28 deletions src/hooks/useAnimationFrame.ts

This file was deleted.

38 changes: 38 additions & 0 deletions src/hooks/useTimeout.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
import { useEffect, useRef } from "react";

export const useTimeout = (
callback: (dt: number, time: number) => void,
interval: number = 1000 / 60 // 60 FPS
) => {
const timeoutRef = useRef<NodeJS.Timeout | null>(null);
const previousTimeRef = useRef<number | null>(null);
const startTimeRef = useRef<number | null>(null);

const animate = () => {
const currentTime = performance.now();

if (startTimeRef.current === null) {
startTimeRef.current = currentTime;
}

const time = currentTime - startTimeRef.current;

if (previousTimeRef.current !== null) {
const deltaTime = time - previousTimeRef.current;
callback(deltaTime, time);
}

previousTimeRef.current = time;
timeoutRef.current = setTimeout(animate, interval);
};

// biome-ignore lint/correctness/useExhaustiveDependencies: animate changes every render
useEffect(() => {
timeoutRef.current = setTimeout(animate, interval);
return () => {
if (timeoutRef.current !== null) {
clearTimeout(timeoutRef.current);
}
};
}, [callback, interval]);
};