Files
shimejic/src/core/----------OLDanimation.ts
T
2026-10-15 18:19:09 +02:00

90 lines
2.7 KiB
TypeScript

/**
* animation.ts — frame sequencing for animated sprites.
*
* Owns: a clip (list of frames + fps + loop mode) and the elapsed time
* inside it. Does not own: what a "walk" is, which clip should be playing,
* or anything about drawing.
*
* The output — `frame` — is a CanvasImageSource, which plugs directly
* into the renderer's `SpriteDraw.image` field with no conversion.
*/
export interface AnimationClip {
/** Ordered frames. Any CanvasImageSource: HTMLImageElement, ImageBitmap, canvas, … */
frames: CanvasImageSource[];
/** Playback rate in frames per second. */
fps: number;
/** Default true. When false, holds the last frame after one pass. */
loop?: boolean;
}
export class Animator {
private clip: AnimationClip | null = null;
private elapsed = 0;
private finished = false;
private active = false;
/** Begin playing a clip. If it's already the current clip, this is a no-op. */
play(clip: AnimationClip | null): void {
if (clip === this.clip) return;
this.clip = clip;
this.elapsed = 0;
this.finished = false;
this.active = clip !== null && clip.frames.length > 0;
}
/** Force a restart of the current clip. */
restart(): void {
if (!this.clip) return;
this.elapsed = 0;
this.finished = false;
this.active = this.clip.frames.length > 0;
}
stop(): void {
this.active = false;
}
/** Advance by `dt` seconds. */
update(dt: number): void {
if (!this.active || !this.clip || this.finished) return;
this.elapsed += dt;
if (!this.clip.loop) {
const duration = this.clip.frames.length / this.clip.fps;
if (this.elapsed >= duration) {
this.elapsed = duration;
this.finished = true;
}
}
}
/** Current frame image, or null if no clip is playing. */
get frame(): CanvasImageSource | null {
if (!this.clip || !this.clip.frames.length) return null;
return this.clip.frames[this.frameIndex];
}
/** Current frame index within the clip. */
get frameIndex(): number {
if (!this.clip || !this.clip.frames.length) return 0;
const raw = Math.floor(this.elapsed * this.clip.fps);
return this.clip.loop ? raw % this.clip.frames.length : Math.min(raw, this.clip.frames.length - 1);
}
/** True when a non-looping clip has reached its final frame. */
get done(): boolean {
return this.finished;
}
/** Time elapsed in the current clip, seconds. */
get time(): number {
return this.elapsed;
}
get currentClip(): AnimationClip | null {
return this.clip;
}
}