Files
OpenFrontIO/src/client/graphics/AnimatedSprite.ts
T
DevelopingTom 7520bc8352 Add ruins and desolation FX on nuke explosions (#847)
## Description:

Add a few animations after a nuke exploded:
- small fire
- big fire
- small smoke
- big smokes


https://github.com/user-attachments/assets/6ef7c1e3-ae3e-4420-aab2-3a3a3630ad98

## Please complete the following:

- [x] I have added screenshots for all UI updates
- [x] I confirm I have thoroughly tested these changes and take full
responsibility for any bugs introduced
- [x] I understand that submitting code with bugs that could have been
caught through manual testing blocks releases and new features for all
contributors

## Please put your Discord username so you can be contacted if a bug or
regression is found:

IngloriousTom
2025-05-22 19:27:07 -04:00

79 lines
1.8 KiB
TypeScript

export class AnimatedSprite {
private frameHeight: number;
private currentFrame: number = 0;
private elapsedTime: number = 0;
private active: boolean = true;
constructor(
private image: CanvasImageSource,
private frameWidth: number,
private frameCount: number,
private frameDuration: number, // in milliseconds
private looping: boolean = false,
private originX: number,
private originY: number,
) {
if ("height" in image) {
this.frameHeight = (image as HTMLImageElement | HTMLCanvasElement).height;
} else {
throw new Error("Image source must have a 'height' property.");
}
}
update(deltaTime: number) {
if (!this.active) return;
this.elapsedTime += deltaTime;
if (this.elapsedTime >= this.frameDuration) {
this.elapsedTime -= this.frameDuration;
this.currentFrame++;
if (this.currentFrame >= this.frameCount) {
if (this.looping) {
this.currentFrame = 0;
} else {
this.currentFrame = this.frameCount - 1;
this.active = false;
}
}
}
}
isActive(): boolean {
return this.active;
}
lifeTime(): number | undefined {
if (this.looping) {
return undefined;
}
return this.frameDuration * this.frameCount;
}
draw(ctx: CanvasRenderingContext2D, x: number, y: number) {
const drawX = x - this.originX;
const drawY = y - this.originY;
ctx.drawImage(
this.image,
this.currentFrame * this.frameWidth,
0,
this.frameWidth,
this.frameHeight,
drawX,
drawY,
this.frameWidth,
this.frameHeight,
);
}
reset() {
this.currentFrame = 0;
this.elapsedTime = 0;
}
setOrigin(xRatio: number, yRatio: number) {
this.originX = xRatio;
this.originY = yRatio;
}
}