/ src / AnimationManager.ts
AnimationManager.ts
 1  import { Animation, AnimationOptions } from './Animation'
 2  
 3  export class AnimationManager {
 4    /** Image qui sert de sprite aux animations */
 5    private readonly image: HTMLImageElement
 6  
 7    /**
 8     * La taille d'une frame doit être fixée car les frames sont référencées par
 9     * des index
10     */
11    private readonly frameWidth: number
12    private readonly frameHeight: number
13  
14    /** Liste des animations */
15    private readonly animations: { [key: string]: Animation }
16  
17    /** Animation courante */
18    private currentAnimation: Animation | null
19  
20    public constructor(
21      image: HTMLImageElement,
22      frameWidth: number,
23      frameHeight: number,
24    ) {
25      this.image = image
26  
27      this.frameWidth = frameWidth
28      this.frameHeight = frameHeight
29  
30      this.animations = {}
31      this.currentAnimation = null
32    }
33  
34    public update(dt: number): void {
35      if (this.currentAnimation instanceof Animation) {
36        this.currentAnimation.update(dt)
37      }
38    }
39  
40    public render(ctx: CanvasRenderingContext2D): void {
41      if (this.currentAnimation instanceof Animation) {
42        this.currentAnimation.render(ctx)
43      }
44    }
45  
46    public addAnimation(
47      name: string,
48      frames: Array<number>,
49      options: AnimationOptions = {},
50    ): void {
51      const animation = new Animation(
52        this.image,
53        frames,
54        this.frameWidth,
55        this.frameHeight,
56        options,
57      )
58  
59      this.animations[name] = animation
60    }
61  
62    public play(name: string, force: boolean = false): void {
63      const nextAnimation = this.animations[name]
64  
65      if (this.currentAnimation !== nextAnimation || force) {
66        this.currentAnimation = nextAnimation
67  
68        nextAnimation.restart()
69      }
70    }
71  }