Improve animation handling

This commit is contained in:
kolaflash
2026-01-17 14:52:42 +01:00
parent 9441e09d07
commit 74a77fa281
8 changed files with 84 additions and 40 deletions
+47
View File
@@ -0,0 +1,47 @@
import { drawSprite, type Sprite } from "#/lib/Sprite.ts";
export const spriteMap = new Map<string, Sprite>();
export type Animation = {
spriteSrc: string;
xIndex: number;
yIndex: number;
frameTime: number;
frameDelta: number;
};
export function createAnimation(
sprite: Sprite,
frameTime: number,
yIndex: number,
): Animation {
const spriteSrc = sprite.image.src;
spriteMap.set(spriteSrc, sprite);
return {
spriteSrc,
xIndex: 0,
yIndex,
frameTime,
frameDelta: 0,
};
}
export function playAnimation(
ctx: CanvasRenderingContext2D,
animation: Animation,
x: number,
y: number,
delta: number,
): void {
const sprite = spriteMap.get(animation.spriteSrc)!;
if ((animation.frameDelta += delta) > animation.frameTime) {
animation.frameDelta = 0;
if ((animation.xIndex += 1) >= sprite.xFrames) {
animation.xIndex = 0;
}
}
drawSprite(ctx, sprite, animation.xIndex, animation.yIndex, x, y);
}
+10 -6
View File
@@ -66,12 +66,16 @@ export const [loadScene, sceneCache] = useWithAsyncCache(
});
}
const instance: Entity<unknown> = structuredClone({
...entityMap.get(entity.name)!,
...entity,
});
entityInstanceMap.get(entity.name)!.instances.push(instance);
try {
entityInstanceMap.get(entity.name)!.instances.push(
structuredClone({
...entityMap.get(entity.name)!,
...entity,
}),
);
} catch (error) {
console.error(entity.name, error);
}
}),
);
},