Sidequest

Drawing the Bird

Let's start by drawing the bird. The good news is we've seen all this code before when we wrote in the Ground class. Let's create a new class, a new instance in main.ts, and add it to the game loop.

1
import { SpriteData } from "#/components/sprite-data";
2
import { Vector2d } from "#/components/vector2d";
3
4
type BirdOptions = {
5
spriteSheet: HTMLImageElement;
6
spriteData: SpriteData;
7
position: Vector2d;
8
};
9
10
export class Bird {
11
spriteSheet: HTMLImageElement;
12
spriteData: SpriteData;
13
position: Vector2d;
14
15
constructor(options: BirdOptions) {
16
this.spriteSheet = options.spriteSheet;
17
this.spriteData = options.spriteData;
18
this.position = options.position;
19
}
20
21
public draw(context: CanvasRenderingContext2D) {
22
context.drawImage(
23
this.spriteSheet,
24
this.spriteData.sourceX,
25
this.spriteData.sourceY,
26
this.spriteData.width,
27
this.spriteData.height,
28
this.position.x,
29
this.position.y,
30
this.spriteData.width,
31
this.spriteData.height
32
);
33
}
34
}

Update main.ts to create a bird instance:

1
import spriteSheetUrl from "#/assets/image/spritesheet.png";
+
import { SpriteData } from "#/components/sprite-data";
3
import { Vector2d } from "#/components/vector2d";
4
import { config } from "#/config";
+
import { Bird } from "#/entities/bird";
6
import { Ground } from "#/entities/ground";
7
import { loadImage } from "#/lib/asset-loader";
8
import { spriteMap } from "#/sprite-map";
9
10
// ...
11
12
const ground = new Ground({
13
position: new Vector2d(0, config.gameHeight - spriteMap.ground.height),
14
spriteData: spriteMap.ground,
15
spriteSheet,
16
scrollSpeed: 120,
17
});
18
+
const bird = new Bird({
+
spriteSheet,
+
position: new Vector2d(config.gameWidth / 4, config.gameHeight / 2),
+
spriteData: new SpriteData(
+
spriteMap.bird.idle.sourceX,
+
spriteMap.bird.idle.sourceY,
+
spriteMap.bird.idle.width,
+
spriteMap.bird.idle.height
+
),
+
});
29
30
// ...

Then add the bird.draw() call beneath ground.draw():

1
ground.draw(context);
+
bird.draw(context);

We draw the bird after the ground so that it appears above the ground.

The bird's looking a little boring, we'll animate it next.